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.

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.

Answers:

Answer

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");
Answer

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");
Answer
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/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.