.data()
Anonymous contributor
Published Dec 6, 2023
Contribute to Docs
The .data()
method is used to bind data to DOM (document object model) elements.
Syntax
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.
Example
Consider an HTML file with an empty list of items:
<!DOCTYPE html><head><h1>D3 Example Page</h1></head><body><ul><!-- Empty unordered list--><li></li><li></li><li></li><li></li></ul></body>
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.selectAll('li').data(nums).join().text((d) => `The value ${d}`);</script>
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:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript:D3 on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn D3
Learn how to create bar charts with D3, the popular interactive data visualization library.With CertificateIntermediate1 hour