* fix: restructure certifications guide articles * fix: added 3 dashes line before prob expl * fix: added 3 dashes line before hints * fix: added 3 dashes line before solutions
2.2 KiB
2.2 KiB
title
| title |
|---|
| Work with Data in D3 |
Work with Data in D3
Problem Explanation
This challenge uses the select, selectAll, append, and text methods seen in previous challenges. It adds 2 new D3 methods: data and enter to target the given data and display an element on the page for each datum
Relevant Links
From the official D3 documentation:
Hints
Hint 1
- After selecting the correct HTML nodes, use the
datamethod with thedatasetvariable passed as an argument to make the D3 object aware of the data
Hint 2
- Use the
entermethod to ensure that your HTML document has enough elements of the type you specified inselectAllfor each datum
Hint 3
- Now that the D3 object is aware of your data and has created enough elements for each datum,
appendthe elements of the specified type and add thetextrequired in the instructions
Solutions
Solution 1 (Click to Show/Hide)
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select('body').selectAll('h2')
.data(dataset)
.enter()
.append('h2')
.text('New Title');
</script>
</body>
Code Explanation
d3targets the D3 objectselect('body')is used toselectthe 'body' element of the HTML documentselectAll('h2')is used toselectAllof the 'h2' elements that are children to 'body'data(dataset)calls the D3datamethod and uses the given dataset as an argumententer()uses the D3entermethod to check the current number of elements selected and create any missing ones according to the amount needed by the datasetappend('h2')takes these newly created elements fromenterand ensures they are created as 'h2' elementstext('New Title')changes the text of every element selected to 'New Title'- The dataset contains 9 datum, so the final solution should show 9 'h2' elements with the text 'New Title'