javascript-d3How do I use the datum method in D3.js?
The datum method in D3.js is used to set or retrieve the data associated with an element. It is often used within the enter() selection to bind data to elements.
Example
var selection = d3.selectAll("div")
.data([1,2,3])
.enter()
.append("div")
.datum(function(d) { // set the data
return d * 10;
});
console.log(selection.datum()); // retrieve the data
Output example
[10, 20, 30]
In the example above, the datum() method was used to set the data associated with the div elements to an array of numbers multiplied by 10. The datum() method was also used to retrieve the data associated with the div elements, which is printed to the console.
Code explanation
d3.selectAll("div")
: This line selects all div elements on the page..data([1,2,3])
: This line binds the data array [1,2,3] to the selected div elements..enter()
: This line creates a placeholder for each data element in the array..append("div")
: This line appends a div element for each placeholder..datum(function(d) { // set the data
: This line sets the data associated with each div element to the value returned by the callback function.return d * 10;
: This line returns the value of each data element multiplied by 10.selection.datum()
: This line retrieves the data associated with the div elements.
Helpful links
More of Javascript D3
- How can I use d3.js to create a zoom scale?
- How do I create a zoomable chart using d3.js?
- How do I implement zooming in a d3.js visualization?
- How do I use the viewbox feature in d3.js?
- How can I create a word cloud using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I use the z-index property with d3.js?
- How do I use d3.js to create visualizations?
- How can I create a website using d3.js?
- How do I use D3.js to create a Wikipedia page?
See more codes...