d3 selector for immediate children

I wouldn't have expected this to work, but it looks like D3 will sub-select any element that is a child of the selection and matches the selector - so this works:

d3.select(this).selectAll('div > ul');

See http://jsfiddle.net/g3aay/2/


@nrabinowitz's solution doesn't work all the time.

In my case, I was trying to do d3.select(this).selectAll(".childNode > *").

So I was trying to get all the immediate children of .childNode. The problem is that this was a nested stack, so .childNode could also appear in the children, which was causing problems.

The best way I found is:

var child = d3.select(this).select(".childNode");
var sel = d3.select(this).selectAll(".childNode > *").filter(function() { 
    return this.parentNode == child.node();
});

d3 selection v2.0 should now have this built in with new selection.selectChildren() / selection.selectChild() methods - see https://github.com/d3/d3-selection/issues/243


If anyone is still interested, d3.select(this.childNodes) was helping me to solve my problem for picking all immediate children. Alternatively, you can use

selection.select(function(){
  return this.childNodes;
})

Tags:

D3.Js