D3 Data Driven Documents

D3 is a JavaScript library which gives power to your front end by providing data to create and delete elements on the page, along with simple updating of that data and other elements on the page. The typical patterns for D3 are enter(), update and exit().remove() and a brief example of each is below.

To get started, you will have to find the element or class you want to do work on. If you are familiar with jQuery, then this should look similar (it’s similar to find()). You can start with the top element and dive into each child to find the one you want. Then you choose .select() or .selectAll(). If you are looking for a single element or the first element with that name use .select(), if you are looking for all the elements with that name use .selectAll(). If you look for a class instead of an element be sure to use the dot, .selectAll(“.trumpet”) or use a hash for IDs, .selectAll(‘#trumpet’).


// Initialize the page, join the data, then set a reference variable so there is less to type later.
var heightValues = [30,40,50];
var myPage = d3.select('body')
.data(heightValues, function(d) {return d;})

// ENTER() Since we have more data than elements on the DOM, we call .enter() and it adds div elements with a specified height from the data above to the DOM tree.
myPage.enter().append('div').attr('height', height)

// UPDATE Let’s update our height with random numbers now. No special function is needed for updating. Find the element or class using .select() or .selectAll() and then reassign the value of the .attr()
myPage.selectAll('div').attr('height', function(d) { return Math.random(); })

// Now if we wanted to delete an element we can remove an item from the data array
heightValues = [30,40];

// REMOVE() Then call .exit() with a .remove() and the element or class without data (the last div element) will be removed from the DOM. If we only called .exit(), the element would be left in the DOM with no data value.