Scott Murray

Tutorials > D3 > Adding elements

Adding elements

Last updated 2015 September 15

One of your first steps will be to use D3 to create a new DOM element. Typically, this will be an SVG object for rendering a data visualization, but we’ll start simple, and just create a p paragraph element.

Begin with this simple HTML template:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 Test</title>
        <script type="text/javascript" src="d3/d3.v3.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            // Your beautiful D3 code will go here
        </script>
    </body>
</html>

Here’s a demo page with that code. Yes, it doesn’t look like much, but open up your web inspector, and you should see something like:

1

Back in your HTML, replace the comment between the script tags with:

d3.select("body").append("p").text("New paragraph!");

Save and refresh (or view the corresponding demo page), and voilà! There is text in the formerly empty browser window, and the following in the web inspector:

2

See the difference? Now in the DOM, there is a new paragraph element that was generated on-the-fly! This may not be exciting yet, but you will soon use a similar technique to dynamically generate tens or hundreds of elements, each one corresponding to a piece of your data set.

Let’s walk through what just happened. In sequence, we:

  1. Invoked D3's select method, which selects a single element from the DOM using CSS selector syntax. (We selected the body.)
  2. Created a new p element and appended that to the end of our selection, meaning just before the closing </body> tag in this case.
  3. Set the text content of that new, empty paragraph to “New paragraph!”

All of those crazy dots are just part of D3’s chain syntax.

Next up: Chaining methods

Interactive Data Visualization for the WebThese tutorials have been expanded into a book, Interactive Data Visualization for the Web, published by O’Reilly in March 2013. Purchase the ebook and print editions from O’Reilly. A free, online version includes interactive examples. Download the sample code files and sign up to receive updates by email.

Follow me on Twitter or watch this RSS feed for other updates.

These tutorials have been generously translated to Catalan (Català) by Joan Prim, Chinese (简体中文) by Wentao Wang, French (Français) by Sylvain Kieffer, Japanese (日本語版) by Hideharu Sakai, Russian (русский) by Sergey Ivanov, and Spanish (Español) by Gabriel Coch.

Also see my video courses, “An Introduction to d3.js: From Scattered to Scatterplot” and “Intermediate d3.js: Charts, Layouts, and Maps.”