yasiDrovi
yasiDrovi

Reputation: 137

How to .querySelectAll() from .getElementsByTagNAme() html element?

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

Answers (3)

Pablo
Pablo

Reputation: 6068

Two things to keep in mind:

  1. getElementsByTagName returns a HTMLCollection object.
  2. You must call Element query methods from an specific DOM node.

Your last JS line needs two changes:

  1. First, you need to select the specific DOM node from the ul collection. Ex: ul[0]
  2. Since you are querying the DOM from to the <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

Jack Bashford
Jack Bashford

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

CertainPerformance
CertainPerformance

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

Related Questions