D3 DOM Selection With D3 JavaScript

D3 DOM Selection

In this episode of working with the awesome D3 JavaScript framework, we’ll take a look at D3 DOM Selection so that we can make good use of the power it provides us. In addition, we’ll need to consider things like our own custom scripts and css, in addition to any other 3rd party libraries that we might want to include in our project. Next up we’ll talk just briefly about the D3 namespace, HTML Configuration, nth-child pseudo selection, as well as modifying selections using D3 JS.

Enabling D3 On Your HTML Page

There are a few ways to handle injecting the D3 library into your page so that you can make use of it’s power. Rather than cover how to do this all manually, we’ll just make handy use of a CDN or content delivery network. I’ve come to love CDNs for their ease of use and consistent behavior along with caching performance gains. So all you have to do to start making use of D3 right away is to paste this line into your page.

Where Should I Place My Own Hand Written D3 Scripts?

Now that we have the library installed on our page, we need a place to contain and collect all of the script that we will write to leverage the D3 library itself. We’ll make this easy and simply create a new JavaScript file to hold this data. We’ll place it in our js directory and name the file d3scripts.js We’ll also include a blank CSS file for any custom sytling we may want to add, as well as bootstrap. Here is the beginnings of our test file that we’ll use to kick the tires on D3.

    <meta charset="UTF-8">
    <title>D3 JavaScript</title>
    <!--The D3 Library CDN style-->
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <!-- Custom JS to leverage D3 -->
    <script src="js/d3scripts.js" charset="utf-8"></script>
    <!-- Any Custom Syles Needed -->
    <link rel="stylesheet" href="css/style.css">
    <!-- And Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<body class="container">

<div class="main">
    <h2>D3 JavaScript</h2>


D3 DOM Selection Capabilities

These methods are namespaced within the d3 object. This is just a fancy way of saying, you need to type d3. before trying to use one of these methods.


Just like you are used to with jQuery, with the d3.select() method, you pass in a selector and the first match is returned to you. It is important to note that if there are several matches on the page, only the first is provided back.


If you do want to return all matches for the selector you use, then the d3.selectAll() method is the one you want to use. We can test both of these out on some simple markup from our sandbox page.



nth-child pseudo selector

The d3.selectAll() method is pretty handy, but maybe you don’t want to clobber everything in the matched set with a new value. What if you only need to select and alter one out of a given five elements, in a specific position? This is where the nth-child css pseudo selector comes in perfectly. Using it, we can specify exactly where we want to select and modify. Let’s consider this list:

    <ul class="list list-unstyled">
        <li class="item">JavaScript</li>
        <li class="item">The DOM</li>
        <li class="item">Scalable Vector Graphics</li>
        <li class="item">jQuery</li>
        <li class="item">Content Delivery Network</li>

We’d like to use the selector engine in D3 to fetch the li that contains jQuery, and update it to say, “jQuery is cool”. Let’s try it out.

nth child pseudo selector

Excellent! By using the nth-child selector, we easily specify the fourth item in the collection, and update the value. Do note that this is not zero based! As programmers, we are used to arrays and collections always starting at 0. With the nth-child selector, this is not the case. It does in fact start at the number 1, so your counting will be easier. The nth-child selector also has some really interesting features to further refine how you can select elements. You can select all even or odd elements using :nth-child(even) and :nth-child(odd) respectively. If you wanted to capture the 3rd element and all elements thereafter, you could do so like this :nth-child(n+3). Maybe you would like to select every third element, or every fifth element. Again, you could do that using :nth-child(3n) and :nth-child(5n) respectively. It is a very useful selector to have a good mastery of. Like anything else, simply test these out and try different approaches to solve whatever selecting problem you may run into.

Modifying Selections Using D3

Selecting elements and data is the first step in working with D3. Once you have your hooks into this data however, what are you going to do with it? Typically you’ll work with or modify it in some way. Here are the methods you use for doing just that. We’ll test them out as well.


The d3.append() method works much like you would expect it to. Basically, you pass in to the method what you would like to append to the selection. Common things to append are HTML elements such as a span or div.


The d3.insert() method is a little more granular than the d3.append(). With append, you don’t really have control on where to place the element. With insert, if you’d like to place an element inside of an unordered list for example, you can do that.


We’ve actually used d3.text() a few times already. As you have seen, it simply takes the text that you pass into the method, and places that text in the element you have selected on the page.


When you want to be able to insert entire chuncks of HTML instead of just plain text, you can use the d3.html() method to do so.


There will be times that you need to delete an element from the page. It is easy to do so using the d3.remove() method.

Here is an example of using some of these D3 methods.
working with selections in D3

So this is pretty slick. What happens in this example is, we select the unordered list and then append a div element to it. By chaining the d3.attr() method to this, we can set an attribute and value for that attribute. As you can see we specify a class, then set the value of that class to one contained in bootstrap. Recall we did include the bootstrap repository via CDN in our sandbox test bed. Finally, we again chain another method. This time it is the d3.html() method to place some HTML markup inside the newly appended div. We didn’t make use of the d3.insert(), d3.text(), or d3.remove() yet, so let’s create another example and do that now.

testing selections in D3

Lastly, if you wanted to remove all the li elements from the page, you could do so with style and grace by using this snippet.


Basic HTML Configuration For D3 JS Summary

We’re starting to gain some momentum in working with D3. Just like most all of the open source technologies that we can easily incorporate into our websites using a content delivery network, so too can we include the D3 library for use in a snap. We’ve also covered how to select various elements using the d3.select() method, the d3.selectAll() method, and the powerful :nth-child selector in combination with the d3.selectAll() method to get any element we desire. Once we get the elements we need, we then looked at how to operate on these elements using methods like d3.append, d3.insert, d3.text, d3.html, d3.attr, and d3.remove.

Leave a Reply