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:
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:
Back in your HTML, replace the comment between the
script tags with:
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:
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:
selectmethod, which selects a single element from the DOM using CSS selector syntax. (We selected the
pelement and appended that to the end of our selection, meaning just before the closing
</body>tag in this case.
All of those crazy dots are just part of D3’s chain syntax.
Next up: Chaining methods →