DEV Community

Sai Kiran
Sai Kiran

Posted on • Edited on

D3js fundamentals Part 5 Joins And Enter/Exit

Last article we learnt about scales which help in converting our data as data point for svg.

Data visualization means working with data. We want to access the data we want in efficient way. Joins helps us to bind data to the DOM element in efficient way.

To join data to DOM you just need to call .data() on the selected d3 element and pass your data as parameter. In the below example we have 5 circles elements. Select all the elements and call .data() by passing the data to it.

.data() function will loop through the data and will bind data to each node one by one. Press F12, reload the page and check the logs. You will find the list of nodes that we selected and expand the first element scroll down to bottom where you can see __data__ which has the respective data bonded to the element which you can access whenever you select that particular element.

Alt Text

If you have observed or not, our data is only 4 in length but we have bonded that data to 5 selected elements. Check the fifth element from the same logs, there will be no __data__ property to it.
D3 gives us easy way to adjust the DOM elements to the data with the help of .enter() function for adding data and .exit() function for removing the data. Both fucntions returns the extra data but .enter() followed by .append() will add extra elements and .exit() followed by .remove() will remove the extra elements.

Remove Example

Append example

Every function will get the bonded data as the call back parameter with which we can do verity for tricks. Like changing the values of its attributes and css properties.

In the example below we are changing the fill color of the circle elements based on its radius. If it is less than 35 its fill color should be of red and otherwise orange. Note here that condition applies to only extra elements as we used the condition after the enter statement. We need again select all the circles in order to make the condition for all.

Top comments (0)