You, Me and D3: A look inside D3.js’ Enter, Update and Exit Selection Methods
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
We then select all new pieces of data with
.enter(), the append an element with a
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
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
Therefore we can now refer to the already-existing nodes by selecting
.ball elements with
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!