I have the following DOM structure:
var parent = document.querySelector(".test");
var navChild = parent.querySelectorAll("ul > li > a");
for (i = 0; i < navChild.length; i++) {
navChild[i].style.backgroundColor = "red";
}
console.log(navChild.lenght);
console.log(navChild);
<!-- begin snippet: js hide: false console: true babel: false -->
<ul>
<li class="test">
<a>ssss</a> <!--this will also be affected -->
<ul>
<li><a>fsfsf</a></li>
<li><a>sff</a></li>
<li><a>ggg</a></li>
</ul>
</li>
</ul>
I want to select the 3 a
tags using vanilla javascript and starting from the li
with the class test. I put this in a parent
variable and then use querySelectorAll to try to get only the a
tags that are inside the next list. However, the nodelist that is returned also includes the very first a
tag even though it's not a descendant. This is my code:
var navChild = parent.querySelectorAll("ul > li > a");
What's really weird is that if I query for just the li
descendants I get only the 3. So I don't understand why when I query for the child descendant of that li
I also get that first a
tag that is two levels up on the DOM.
I know I could do this using jQuery but I don't want to use it.
EDITED to show how I'm setting the parent variable
I'm trying to add those a
tags to the childs
variable after I've hit the enter keyboard button while on the first a
tag that I don't want to include in the childs node list.
var alinks = document.querySelectorAll('.test > a');
[].forEach.call(alinks, function(link){
link.addEventListener('keyup', function(e){
e.preventDefault();
if(e.keyCode === 13) {
var linkParent = e.target.parentElement;
var childs = menuParent.querySelectorAll('ul > li > a');
}
})
});
When I log linkParent
it is correctly being set as the li
with class test
. I don't understand why then if I run the query from there it still includes the very first a
tag. As I previously stated, if I query just ul > li
it gives me the correct li
tags.