Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 803
QueueHammer Avatar asked Nov 13 '13 14:11

QueueHammer


People also ask

Is d3 similar to jQuery?

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.

What is d3 select?

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.

Which is or are the main selection in d3?

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.


2 Answers

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
like image 197
Lars Kotthoff Avatar answered Nov 04 '22 06:11

Lars Kotthoff


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.

like image 26
friek108 Avatar answered Nov 04 '22 07:11

friek108