The filter element is based on the existence of a child node

If I wanted to filter elements based on the existence of their child nodes, how would I do this in d3.js ?

For example, in this html structure, how would I select <li> elements that have child <a> elements?

 <ul> <li><a href="#">Link 1</a></li> <li>Bullet</li> <li><a href="#">Link 2</a></li> <li><a href="#">Link 3</a></li> <li>Bullet</li> </ul> 

For those who do not know, it is perfectly normal to ask and answer your questions ...

+4
source share
2 answers

Use the filter() function:

 var ul = d3.select("ul"); var lis = ul.selectAll("li").filter(function() { return ! d3.select(this).select("a").empty(); }); 
+3
source

You cold solve the problem using your own Javascript:

First you can select all the β€œa” elements inside the β€œli” element:

 var childLinks = document.querySelectorall("ul li a"); // Supported By IE8+ 

Then you can choose a parent for each of them:

 childLinks[0].parentNode 

Native methods should be faster.

+2
source

All Articles