简体   繁体   中英

Why selectAll(“element”) is important in d3js while generating a chart

I'm learning d3js these days, Following is an example I have tried with the help of d3js documentation.

<script>
    var data = [4, 8, 15, 16, 23, 42];

    d3.select(".chart").selectAll("div").data(data).enter().append("div").style("width", function(d){return d * 10 + "px"; }).text(function(d){return d;}).attr("class", "bar");
</script>

I'm not clear in why selectAll() is important in this code snippet. Without selectAll() also we can generate the chart, but it's creating outside of the body tag. Can any one help me to understand this. What is the role of selectAll() in here.

Thanks.

The selectAll statement allows to manipulate a set of DOM elements, with or without data binding. For instance, this will modify all the paragraphs in a page:

// Select all the paragraphs in the document and set the font color to red
d3.selectAll('p').style('color', 'red');

In D3, you manipulate DOM elements by joining a selection of DOM elements (which may exist of not) to elements in an array. I will rewrite your code for clarity:

// Data Array
var data = [4, 8, 15, 16, 23, 42];

// Bind the array elements to DOM elements
var divs = d3.select(".chart").selectAll("div").data(data);

// Create divs on the enter selection
divs.enter().append("div");

// Update the style and content of the div elements
divs.style("width", function(d){return d * 10 + "px"; })
    .text(function(d){return d;}).attr("class", "bar");

// Remove divs on the exit selection
divs.exit().remove()

Suppose that you have a div classed chart , and that is has nested divs:

<div class="chart">
    <div></div>
    <div></div>
</div>

When you do select('chart').selectAll('div') , you are selecting all the div elements inside the div of class chart. In this case, we have two of such div elements. By binding the selection with the data array select('chart').selectAll('div').data(data), several things happen:

  • The existing div elements are bound to the first and second elements of your array.
  • The enter selection is created. This selection contains 4 placeholder DOM elements. We will append a div element to each one with .append('div') . The enter selection will be appended to the divs selection.
  • If there are more divs than data elements, the remaining DOM elements are stored in the exit selection, and could be removed with divs.exit().remove() .

You can learn more about selections by reading Mike Bostock's excellent tutorial How Selections Work .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM