Now that you’ve selected the elements and understand a bit about selections, let’s insert and associate data per element. You accomplish this with one main method: .data().

The .data() method takes an array of any type as its parameter and binds a datum to each element in the selection returned by .selectAll():

let dataset = [55,34,23,22,59]; d3.selectAll("p") .data(dataset);
  • If the n is the length of the dataset passed into .data() and there is an equal or greater number of <p> elements, then every step that follows .data() in the chain is executed n number of times. In the example above, we have five items inside dataset and we assume there are five <p> elements in the HTML. Every instruction that follows the .data() method is therefore executed five times.
  • In this example, we used an array of numbers, but we could have just as easily used an array of complex objects. The .data() function accepts an array of any type.

So is the data associated with the elements or the selection? With the elements! The data is bound to elements as a property, we’ll explore this in later steps. Binding data to the elements allows the data to remain associated with the elements on the DOM even after you want to re-use the .selectAll() method to create a new selection.



There are 15 div elements inside index.html and the code has created a selection for them inside a variable named divSelection. Bind the videoData by using the .data() method. Note that videoData is an array of objects. We’ll explain the .text() portion of this code block in the following exercise:

divSelection .data(videoData) .text(function(d) {return d});

For now, notice what gets assigned to each <div> is the string representation of the objects inside videoData. We’ll learn how to leverage data in elements in the next exercise. Click next when you’re ready!

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?