Reputation: 137
Let suppose I have HTML like:
<html>
<body>
<ul>
<li>list</li>
<li>2</li>
<li>3</li>
</ul>
<div>div</div>
<p>something else</p>
</body>
</html>
and I want to get all UL elements:
var ul = document.getElementsByTagName("ul");
Now I would like to get all list elements:
var allListElements = ul.querySelectorAll("ul > li");
var ul = document.getElementsByTagName("ul");
var allListElements = ul.querySelectorAll("ul > li");
<ul>
<li>list</li>
<li>2</li>
<li>3</li>
</ul>
<div>div</div>
<p>something else</p>
However this is not working... but getElementById
is working fine with querySelectAll()
. So how to make to work HTMLcollection or NodeList with querySelectorAll()
?
Upvotes: 0
Views: 561
Reputation: 6068
Two things to keep in mind:
getElementsByTagName
returns a HTMLCollection
object.Element
query methods from an specific DOM node.Your last JS line needs two changes:
ul
collection. Ex: ul[0]
<ul>
node you must exclude this element from the query. Ex: ul[0].querySelectorAll("li")
Please find the final edits below:
var ul = document.getElementsByTagName("ul");
var allListElements = ul[0].querySelectorAll("li");
console.log(allListElements)
<html>
<body>
<ul>
<li>list</li>
<li>2</li>
<li>3</li>
</ul>
<div>div</div>
<p>something else</p>
</body>
</html>
Upvotes: 1
Reputation: 44135
The ul > li
elements are not contained inside the ul
- they're on the document
. Use that query string:
var allListElements = [...document.querySelectorAll("ul > li")];
console.log(allListElements);
<ul>
<li>list</li>
<li>2</li>
<li>3</li>
</ul>
<div>div</div>
<p>something else</p>
Upvotes: 0
Reputation: 371233
Just call querySelectorAll
with the ul > li
query string alone, on the document
:
var allListElements = document.querySelectorAll("ul > li");
console.log(allListElements);
<ul>
<li>list</li>
<li>2</li>
<li>3</li>
</ul>
<div>div</div>
<p>something else</p>
If you already have an HTMLCollection that you need to effectively call querySelectorAll
on, it'd be more complicated, you'd have to call querySelectorAll
on each element in the HTMLCollection:
var uls = document.getElementsByTagName("ul");
var allListElements = [...uls].reduce((a, ul) => {
a.push(...ul.querySelectorAll('li'));
return a;
}, []);
console.log(allListElements);
<ul>
<li>list</li>
<li>2</li>
<li>3</li>
</ul>
<div>div</div>
<p>something else</p>
Upvotes: 2