How to use querySelectorAll() to search for a specific tag derived from an element that has an x class?

Asked

Viewed 309 times

1

Someone could help me use the .querySelectorAll() to find all paragraph elements derived from items that have a classe x?

1 answer

2


If you want to find all the paragraphs <p> within an element with a class x you use the selector ".x p":

document.querySelectorAll(".x p");

If you only want the elements <p> direct children, use ".x > p":

document.querySelectorAll(".x > p");

All elements within the class:

var els = document.querySelectorAll(".x p");
for(var x=0; x<els.length; x++){
   console.log(els[x]);
}
<div class="x">
   <p>paragrafo 1</p>
   <p>paragrafo 2</p>
   <div class="y">
      <p>paragrafo 3</p>
      <div class="z">
         <p>paragrafo 4</p>
      </div>
   </div>
</div>

<div class="x">
   <p>paragrafo 5</p>
   <p>paragrafo 6</p>
   <div class="y">
      <p>paragrafo 7</p>
      <div class="z">
         <p>paragrafo 8</p>
      </div>
   </div>
</div>

Only the direct children:

var els = document.querySelectorAll(".x > p");
for(var x=0; x<els.length; x++){
   console.log(els[x]);
}
<div class="x">
   <p>paragrafo 1</p>
   <p>paragrafo 2</p>
   <div class="y">
      <p>paragrafo 3</p>
      <div class="z">
         <p>paragrafo 4</p>
      </div>
   </div>
</div>

<div class="x">
   <p>paragrafo 5</p>
   <p>paragrafo 6</p>
   <div class="y">
      <p>paragrafo 7</p>
      <div class="z">
         <p>paragrafo 8</p>
      </div>
   </div>
</div>

Consider direct children the elements in the first level within the hierarchy of parent element.

  • Thanks bro, I tested here and finally get.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.