简体   繁体   English

选择<li>子节点但不选择带有vanilla JavaScript的孙子节点

[英]Selecting <li> child node but not grandchildren with vanilla 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>

I'm trying to pull the text from each of the first anchors (link a, link b, link c), but am having some problems. 我试图从每个第一个锚点(链接a,链接b,链接c)中提取文本,但是我遇到了一些问题。

Most recently, I've tried: 最近,我尝试过:

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);
}

but this jumps into the <ul> s within the <li> s. 但这会跳进<li><ul>

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. 我真正需要的是能够获得顶层<li><a>引用,并且能够在<li><a>中获取文本。

To get direct children of the ul#menu use children HTMLCollection: 要获得ul#menu直接children节点,请使用children节点HTMLCollection:

var X = document.getElementById("menu").children;

Alternatively, you could select the same collection of li elements with querySelectorAll method using direct children selector : 或者,您可以使用直接子选择器使用querySelectorAll方法选择相同的li元素集合:

var X = document.querySelectorAll("#menu > li");

Why not using document.querySelectorAll for this. 为什么不使用document.querySelectorAll It is wide supported: http://caniuse.com/#feat=queryselector 它受到广泛支持: http//caniuse.com/#feat=queryselector

And it is easy to query like in css style. 并且很容易像css样式一样查询。 Hope it help. 希望它有所帮助。 Here is the documentation of how to use it: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll 以下是如何使用它的文档: https//developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Also can be interested in this for selecting single item: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector 也可以对此选择单个项目感兴趣: https//developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

var childNodes = document.querySelectorAll("#menu > li");
var X = document.getElementById("menu");
var Y = X.getElementsByTagName("li");



for (var i = 0; i < Y.length; i++) {
 if(Y[i].parentNode.getAttribute('id')=='menu') {


   var Z = Y[i].getElementsByTagName('a');
   console.log(Z[0].innerHTML);

   }




}

Demo: http://jsfiddle.net/txmvshpa/3/ 演示: http//jsfiddle.net/txmvshpa/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM