选择< li>子节点,但不包括具有普通JavaScript的孙子节点 [英] Selecting <li> child node but not grandchildren with vanilla JavaScript
本文介绍了选择< li>子节点,但不包括具有普通JavaScript的孙子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些如下设置的列表:
I have some lists set up like the following:
<ul id="menu">
<li>
<a href="#">link a</a>
<ul>
<li>...</li>
<li>...</li>
</ul>
</li>
<li>
<a href="#">link b</a>
<ul>
<li>...</li>
<li>...</li>
</ul>
</li>
<li>
<a href="#">link c</a>
<ul>
<li>...</li>
<li>...</li>
</ul>
</li>
</ul>
我正在尝试从第一个锚点(链接a,链接b,链接c)中提取文本,但是遇到了一些问题.
I'm trying to pull the text from each of the first anchors (link a, link b, link c), but am having some problems.
最近,我尝试过:
var X = document.getElementById("menu");
var Y = X.getElementsByTagName("li");
for (var i = 0; i < Y.length; i++) {
var Z = Y[i].getElementsByTagName('A');
console.log(Z[0].innerHTML);
}
,但这会跳到<li>
内的<ul>
中.
but this jumps into the <ul>
s within the <li>
s.
我真正需要的是能够获取顶级<li>
的<a>
引用,还能够在这些<li>
的<a>
中抓取文本.
What I need really is to be able to get the <a>
reference to the top level <li>
s and also be able to grab the text within the <a>
of those <li>
s.
推荐答案
To get direct children of the ul#menu
use children
HTMLCollection:
var X = document.getElementById("menu").children;
或者,您可以使用直接子选择器:
var X = document.querySelectorAll("#menu > li");
这篇关于选择< li>子节点,但不包括具有普通JavaScript的孙子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文