Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 selector for immediate children

Tags:

d3.js

I can obviously do this:

d3.selectAll('div#some-div>ul') 

But what if I'm using a DOM node or existing D3 selection:

d3.select(this).selectAll('ul') 

will get me all descendent ULs. So, if

var div = d3.select('div')  

got me this node:

<div>   <ul>     <li>foo       <ul><li>bar</li></ul>     </li>   <ul> </div> 

Then

var uls = div.selectAll('ul')  

will get me two ULs. I guess I could distinguish a top level one like:

uls.filter(function() { return this.parentNode === div.node() } 

So, I've answered my own question. Maybe it will be useful to someone. Or maybe someone can recommend a less ugly solution.

Even better, Alain Dumesny, whose answer below is belatedly selected as correct, posted this as an issue to D3 and got the problem fixed, kludge-free, at the source! (I would copy it in here for convenience, but then people might not scroll down and cast greatly deserved upvotes for his heroic feat.)

like image 623
Sigfried Avatar asked Dec 13 '13 15:12

Sigfried


People also ask

What is D3 selectAll?

selectAll() function in D3. js is used to select all the element that matches the specified selector string. Syntax: d3.selectAll("element") Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.

How does D3 select work?

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.


1 Answers

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/

like image 140
nrabinowitz Avatar answered Sep 20 '22 08:09

nrabinowitz