A d3.select… equivalent to jQuery.children()

后端 未结 5 1759
感动是毒
感动是毒 2021-01-07 21:03

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 orig

相关标签:
5条回答
  • 2021-01-07 21:04

    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} > *`)
    
    0 讨论(0)
  • 2021-01-07 21:05

    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();
        return this
            .selectAll(d)
            .filter(function(){ return that == this.parentNode; });
    };
    
    0 讨论(0)
  • 2021-01-07 21:11

    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
    
    0 讨论(0)
  • 2021-01-07 21:14

    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() { return this.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.

    0 讨论(0)
  • 2021-01-07 21:27

    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.

    0 讨论(0)
提交回复
热议问题