If I wanted to filter elements based on the existence of their child nodes, how would I do that in d3.js
?
For example in this html structure, how would I select the <li>
elements that have children <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 don't know, it's perfectly okay to ask and answer your own questions...
If I wanted to filter elements based on the existence of their child nodes, how would I do that in d3.js
?
For example in this html structure, how would I select the <li>
elements that have children <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 don't know, it's perfectly okay to ask and answer your own questions...
Share Improve this question edited Jan 18, 2021 at 12:38 CommunityBot 11 silver badge asked Jun 25, 2012 at 20:12 WexWex 15.7k10 gold badges67 silver badges107 bronze badges 14- 3 @Recursed: Why wouldn't he? StackOverflow allows this as long as it's not a duplicate. – user1106925 Commented Jun 25, 2012 at 20:16
- 2 @Xander: If you click the Ask Question button, you'll see that StackOverflow actually has a feature that lets you post a Question and Answer at the same time. – user1106925 Commented Jun 25, 2012 at 20:18
- 3 Wow, I'm a little disappointed, having been quite misled from this article: blog.stackoverflow./2011/07/… – Wex Commented Jun 25, 2012 at 20:19
- 2 If down-voters are down-voting because they don't like the self Q/A style, then they're down-voting for the wrong reason. You should be rating the quality of the question and answer. Read the FAQ and you'll see that this is explicitly permitted. – user1106925 Commented Jun 25, 2012 at 20:19
- 4 @Esailija - I'm confused, because in the article it says that "it is explicitly encouraged" – Wex Commented Jun 25, 2012 at 20:49
2 Answers
Reset to default 3Use the filter()
function:
var ul = d3.select("ul");
var lis = ul.selectAll("li").filter(function() {
return ! d3.select(this).select("a").empty();
});
You cold solve the problem using native Javascript:
First you can select all "a" elements inside a "li" element:
var childLinks = document.querySelectorall("ul li a"); // Supported By IE8+
Then you can select, for each of them, the parent:
childLinks[0].parentNode
Native methods should be faster.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745246320a4618427.html
评论列表(0条)