So far, our code has been associating data with existing elements inside our index.html file. What would happen if those elements weren’t already in there? We previously mentioned the idea of “hypothetically” selecting elements so that we could prep them to bind data. How do we turn theoretical elements into real ones to visualize with data? With the .enter()
and .append()
methods!
But first, a quick refresher on the .data()
method. The .data()
method is invoked on a selection and takes a parameter of an array of any type. It returns an update selection with the data bound to the elements. This update selection works as the object invoked on the next step:
The
.enter()
method consolidates the difference between the number of existing elements in the selection and the number of elements in the dataset. It is invoked on the update selection that.data()
returns. If there are more data points than existing “selected” elements,.enter()
creates placeholder elements and returns an enter selection which specifies which elements need to be added. For example, if there were 0 existing elements in the update selection and 10 data points, enter would compute 10 elements in the enter selection. If there were 3, then it would compute 7 in the enter selection. The.enter()
method does not actually append the elements, it just computes how many need to be added.Lastly the
.append("element")
method takes a string parameter with the element name you wish to append, it then analyzes the selection that gets handed off to it, and generates the specified elements on the DOM. It returns a reference to the elements it created.
Note: If you ever want to analyze the data in the selection and log it to the console, you can always use the .nodes()
method on your selection. This method will log the array of grouped nodes in the selection.
After making a selection, creating a new visualization, whose elements are not already in the DOM, usually follows the .data()
.enter()
and .append()
pattern:
let dataset = [55,34,23,22,59]; d3.select("body") .selectAll("div") .data(dataset) .enter() .append("div");
- Everything after
.data()
will therefore get executed five times - The
.enter()
method created five placeholder elements because there were nodiv
elements in the DOM - Five div’s were appended with the div elements
- Those divs each have a
_data_
property with the values of55
,34
,2
,22
,59
, respectively - Each step of the chain returned a reference to those elements.
Instructions
Notice that in this exercise, there are no div
elements inside index.html. We will be adding those elements with .enter()
and .append()
.
After the .data()
method, add the two methods and pass in the string 'div'
to the .append()
method so that it may generate the div
belonging to every datum in the dataset. Be sure to add these steps in the chain right after .data()
but before .text()
. Take a second to note .enter()
will compute the fifteen elements, and .append()
will insert them.