Skip to content Skip to sidebar Skip to footer

A D3.select... Equivalent To Jquery.children()

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. Th

Solution 1:

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

Solution 2:

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.

Solution 3:

You can also select children just with a CSS selector. Here what's I'm doing to select child from index:

d3.select(`#${parentId} > *:nth-child(${index + 1})`)

so I suppose this works:

d3.selectAll(`#${parentId} > *`)

Solution 4:

Late to the party, but at least in d3 version 4, selection.selectAll() can take a function whose result is an array that contains the new elements to select based on the selected element in the previous selection:

var parent = d3.selectAll(".myParentClass");
var children = parent
    //Convert selection to selection representing the children
    .selectAll(function() { returnthis.childNodes; })
    //Apply filter to children
    .filter('g')
    ;

The primary benefit of this approach compared to the previous answers are that the selection.data() function will still work correctly. The previously proposed methods, which assign results from a new, separate d3.select() call, do not allow this.

Solution 5:

Like says Lars, there is no equivalent to 'children()' method in D3, but here left a little extension to d3.selection prototype i wrote. I hope must help you (so late).

d3.selection.prototype.children = function(d){
    var that = this.node();
    returnthis
        .selectAll(d)
        .filter(function(){ return that == this.parentNode; });
};

Post a Comment for "A D3.select... Equivalent To Jquery.children()"