I'm using d3 to append some elements on enter() and then update them later. However, the next time i try to select those elements the selection is much larger than the original. This is because the original selection elements now have children that are the same type e.g.; <g>
, <svg>
. I expected selectAll() to only work at the first decedent level like jQuery.children() is there an equivalent in d3? If not whats the most efficient way to shim that?
D3 is usually used for data visualization but jQuery is used for creating web apps. D3 has many data visualization extensions and jQuery has many web app plugins. Both are JavaScript DOM manipulation libraries, have CSS selectors and fluent API and are based on web standards which makes them look similar.
select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.
Selection methods come in two forms: select and selectAll: the former selects only the first matching element, while the latter selects all matching elements in document order. The top-level selection methods, d3.
There's no equivalent to jQuery.children()
. This is usually handled by assigning a distinguishing class to the elements you want to select together, e.g. something like this.
svg.selectAll("g").data(data)
.enter()
.append("g")
.attr("class", "parent")
.append("g")
.attr("class", "child");
svg.selectAll("g"); // all g elements
svg.selectAll("g.parent"); // only parents
svg.selectAll("g.child"); // only children
Here is a much better way to do it:
var parent = d3.selectAll(".myParentClass");
parent.each(function(d,i) {
var children = d3.selectAll(this.childNodes);
console.log(children);
});
This way you don't need to unnecessarily add classes to what could be 100's of (or even more) child nodes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With