Would anyone help me use .querySelectorAll()
to find all paragraph elements derived from elements that have a classe
x?
Would anyone help me use .querySelectorAll()
to find all paragraph elements derived from elements that have a classe
x?
If you want to find all the <p>
paragraphs within an element with a x
class you use the ".x p"
:
document.querySelectorAll(".x p");
If you only want <p>
pendent 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>
Direct children only:
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 elements on the first level within the parent-element hierarchy.