D3 is an interactive JavaScript library for data visualization that uses Scalar Vector Graphics (SVG) coupled with HTML and CSS to output charts and figures that illustrate the numeric data. To display charts and figures, you need to make use of a data set that can be loaded from a .csv
file or be hardcoded as an array. You can add this dataset to your figure by selecting the containers, but what if the number of items in the dataset does not match the number of containers selected? This is where the enter()
and exit()
method of D3 come in.
The
enter()
andexit()
method allows you toappend
orremove
containers according to the size of your dataset.
enter()
Let’s take a look at the code below. You should focus on the highlighted lines (31 - 51). The code above line 31 is used to style the div
containers and display the button. After reading the code, press the RUN button and then press the button displayed in the output.
Observe two things:
div
containers.Therefore, when we try to add the data in our div
containers, it will just add the first three items and omit the rest.
To cater to this problem, add the enter()
method – it will return an enter selection that represents elements that need to be added. This method is usually followed by append()
, which adds elements to the DOM:
.enter()
.append("div")
Now, after adding the enter()
and append()
method, observe how all of the dataset’s items are printed:
exit()
Take a look at the code below – you should focus on the highlighted lines (31 - 51). The code above line 31 is used to style the div
containers and display the button. After reading the code, press the RUN button, then press the button displayed in the output.
Observe two things:-
div
containers is still the same at three.div
containers.Therefore, when we try to add data in our div
containers, it adds data to the first container but leaves the following two containers empty because there is no item in the dataset to fill them.
To cater to this problem, add the exit()
methodremove()
:
.exit()
.remove()
After adding the exit()
and remove()
methods, notice how all the extra div
containers are removed.
Free Resources