Reputation: 59
Is there a preference between using
d3.selectAll()
and
svg.selectAll()
when
var svg = d3.select("#someChart")
.append("svg")
.attr("width", w)
.attr("height", h);
when dealing with(creating, removing) elements in the svg tag?
Upvotes: 1
Views: 394
Reputation: 25187
As AJ_91 pointed out, d3.selectAll(...)
searches the entire document, whereas svg.selectAll(...)
limits the search to the SVG in the selection. The latter is expectedly more performant for large documents.
However, there's another important difference: If the var svg
references a d3 selection that contains more than a single element then a subselection like svg.selectAll('path')
will select all <path>
s within each <svg>
as expected, but the resulting selection will also maintain "awareness" of the "cousin" relationship between <path>
s that have different <svg>
parents.
This is called nested selections as bostock explains here. Nested selections are used for constructing tables, since tables imply a 2-level hierarchy (n rows then m columns per row). The nested-svg-selection analog to tables would be if you have a multi-level dataset from which you wanted to create multiple SVG's, each of which contains multiple trendline paths (or multiple barchart <rect>
s, etc).
Upvotes: 2