For data visualization it is, of course, necessary to be able to access data. For now we will work with static data we hard-code in our HTML file. Inside the script tag, define a JavaScript array:
const data = [10, 12, 15, 18, 25];
We can bind this data to HTML elements using the .data(data) method after the selection.
d3.selectAll("p").data(data).append("text").text(" 123 ")
So now if we have the same number of items in our array as we have paragraphs, each of the paragraphs get its text set.
And that code is also executed here. So we have "123" behind all p-tags. But what if we don't want to create the elements beforehand? That's where the enter-function comes into place:
Usually we don’t want to create our elements beforehand so that they match the number of data-items in our array. That’s why d3 provides the .enter() method that tells the browser what to do if there are not enough HTML-elements for the number of data items. ( .enter() will be explained more thoroughly later in the tutorial)
Consequently, we can use the following code to create paragraphs on the fly if we do not already have enough in our document.
d3.select("#enterarea").selectAll("samples").data(data).enter().append("p").text("Sample text");
This is an important concept in D3, as it lets us select elements which do not yet exist. We can try it: Push the button, and you can see, that we create for each data element one text:
#enterarea
But we also want our changes to be dependent on the different data-items. For this we can use functions, a concept you should be familiar with from other languages. In D3 we often use anonymous functions that only differ from normal functions by not having a name, and which thus cannot be reused.
d3.select("#enterarea").selectAll("samples").data(data).enter().append("text").text(d => d);
The known equivalent to this would be:
d3.select("#enterarea").selectAll("samples").data(data).enter().append("text").text(function(d) {return d;});
The parameter d is provided as first argument to anonymous functions by D3 and holds the data elements. Optionally, you can also pass the index of the data-item as second parameter to your functions.
d3.select("#enterarea").selectAll("samples").data(data).enter().append("text").text((d,i) => i)