You, Me and D3: A look inside D3.js’ Enter, Update and Exit Selection Methods

As many of you may already know, D3.js is a Javascript library that provides its developers with (supposedly) simple methods that translates data to dynamic visualizations on a browser’s Scalable Vector Graphics container, or more commonly referred to as the SVG. This entire library is essentially built upon three selection tools; Enter, Update and Exit. Correct usage of these built-in methods will open the doors to creating stunning data visualizations, as it allows for the use of styling and animations in a very seamless manor.

From a very high-level, these three methods are essentially just selection tools to help with dynamically picking out the specific nodes that are new and/or already exist on the page. These selections can still be achieved via traversing the DOM with jQuery for example, but doing so would require the use of loops and tons of if statements.

The Enter Selection

This method compares the number of existing nodes with the number of pieces of data associated with those nodes, then selects the data that is not yet visualized on the page. With this selection, you can then append new nodes and apply any transitions or graphics to signify this change.

In the example below, we initially select all DOM elements with a class of .ball, then join it with our data.

let circles = svg
.attr(‘class’, ‘ball’)

We then select all new pieces of data with .enter(), the append an element with a .ball class.

The Exit Selection

Similar to the Enter Selection, the Exit method selects all nodes that no longer have data associated with it. Think a sliced array for example. Since the popped element is no longer needed, neither is the visualization originally associated with it. To remove these unneeded nodes from the SVG, use selection.exit().remove(); .

The Update Selection

Usage of this in D3 is a bit less explicit than both the Enter and Exit methods. First of all, there isn’t a .update() method that you can invoke to select the nodes that need to be updated. A simple line of thought that helped me understand this selection was: All Nodes — (New Nodes + Old Nodes) = Updated Nodes .

Building on our previous example, we now define a new variable for all the new pieces of data that are going to be rendered.

let circles = svg
let newCircles = circles
.attr('class', 'ball')

Therefore we can now refer to the already-existing nodes by selecting circles .ball elements‘.circle’)

Since the new data will be associated with newCircles and not circles, we are now effectively selecting all DOM elements with a class of .ball that were previously on the page.

In summary, it helps to keep in mind that each of these methods in D3 is simply a selection method that compares the number of pieces of data and the DOM elements associated with it. An illustration to help with this idea:

Thanks for reading!