Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Dec 6, 2023
Contribute to Docs

The .data() method is used to bind data to DOM (document object model) elements.


selection.data(data[, key]);
  • selection: The selection of DOM elements to which data will be bound.
  • data: The array of data to be bound to the elements.
  • key (optional): A key function to determine how the data is joined to the given elements. If not provided, D3 uses the index element.


Consider an HTML file with an empty list of items:

<!DOCTYPE html>
<h1>D3 Example Page</h1>
<!-- Empty unordered list-->

These elements can be selected and populated with some data using the following code:

<div id="container"></div>
<script type="module">
import * as d3 from 'https://cdn.jsdelivr.net/npm/d3@7/+esm';
const nums = [10, 20, 30, 40];
const numList = d3.select('ul');
const items = numList
.text((d) => `The value ${d}`);

In this example, the .data() method is used to bind the array of numbers to the list items (li) in the ul element. It gives the following output:

D3 generated list of values

All contributors

Looking to contribute?

Learn JavaScript:D3 on Codecademy