1
Someone could help me use the .querySelectorAll()
to find all paragraph elements derived from items that have a classe
x?
1
Someone could help me use the .querySelectorAll()
to find all paragraph elements derived from items that have a classe
x?
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.
Browser other questions tagged javascript dom elements
You are not signed in. Login or sign up in order to post.
Thanks bro, I tested here and finally get.
– Wemerson Nino