javascript - Filtering element based on existence of child node - Stack Overflow

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

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
 |  Show 9 more ments

2 Answers 2

Reset to default 3

Use 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信