Selecting
  • child node but not grandchildren wi
  • 2020-04-10 15:25发布

    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.

    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.

    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.

    3条回答
    ▲ chillily
    2楼-- · 2020-04-10 16:00

    To get direct children of the ul#menu use 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:

    var X = document.querySelectorAll("#menu > li");
    
    查看更多
    We Are One
    3楼-- · 2020-04-10 16:08
    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/

    查看更多
    Luminary・发光体
    4楼-- · 2020-04-10 16:15

    Why not using document.querySelectorAll for this. It is wide supported: http://caniuse.com/#feat=queryselector

    And it is easy to query like in css style. Hope it help. Here is the documentation of how to use it: 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

    var childNodes = document.querySelectorAll("#menu > li");
    
    查看更多
    登录 后发表回答