So once we’ve associated the data with the elements, how do we access the data and start manipulating our elements based on those values? You’ll need a function with a d param to access each datum associated per element. Think of the d as representing the d in data or datum. Remember that the steps that follow .data() method are executed the total number of elements in the dataset.

In the previous exercise, you pasted an anonymous function with a d parameter. This is because the d parameter represents the value bound to each element in the d3 chain. Say we wanted to change the text inside a div to display the numbers in the array as text:

let dataset = [55,34,23,22,59]; let svg = d3.select("body") .selectAll("div") .data(dataset) .text(function(d) { return d; });
  • In this example, the .text() method took an anonymous function with a d parameter that returns the data value inside each of the div elements. d3 will append that value as the text inside each of the five div elements it created from the dataset array. Note: If the data were of type object, it would append the entire object and we could access each of their properties accordingly.

  • The .data() method assigns the correct value to the d parameter, or the first parameter, for the elements in question.

  • The functions you use don’t always need to be anonymous, but you do need to include a d parameter, or a first argument, if you want to access the data. You can also optionally include an i parameter, or second parameter, if you want to access the index. Your JavaScript functions can be named and as complex as you wish, but for clarity’s sake, we used an anonymous one that simply returns the d value in this example. If we wanted to introduce more complicated logic like conditionals, a loop, or append other text, we could achieve this just like we would in the body of any other function.



The values inside of videoData array are objects. Use the .text() method and pass in an anonymous function that uses the d parameter to return the d.title and d.amount formatted as a string like:

d.title + ": " + d.amount + " views"

Click “Run” and observe the output. Congrats! You were able to customize your data-driven elements based on data bound to them. We’ll keep building on this knowledge.

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?