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.
To get direct children of the
ul#menu
usechildren
HTMLCollection:Alternatively, you could select the same collection of
li
elements withquerySelectorAll
method using direct children selector:Demo: http://jsfiddle.net/txmvshpa/3/
Why not using
document.querySelectorAll
for this. It is wide supported: http://caniuse.com/#feat=queryselectorAnd 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