Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using querySelectorAll to target nested elements

How do I use querySelectorAll to select <p> with parent <div class="entry-content"> only?

Eg.

<div>
    <p>ParagraphA</p>
    <p>ParagraphB</p>
</div>
<div class="entry-content">
    <p>Paragraph1</p>
    <p>Paragraph2</p>
    <p>Paragraph3</p>
</div>
    <p>Paragraph4</p>
    <p>Paragraph5</p>

I only want Paragraph1 ~ Paragraph3 to be selected.

I'm currently using var x = document.querySelectorAll("p"); which is selecting everything.

var x = document.querySelectorAll("div > p"); is very closed to getting what I need, but I need to ensure only selecting all <p> elements within the <div class="entry-content"> with class specified.

How can this be modified to accomplish the task?

like image 897
KDX Avatar asked Dec 01 '22 12:12

KDX


2 Answers

Specify the div's class:

document.querySelectorAll('div.entry-content > p');
like image 130
Johnny Bueti Avatar answered Dec 04 '22 02:12

Johnny Bueti


var entryContent = document.querySelector('.entry-content');//matches first
var p = entryContent.querySelectorAll("p"); //matches all
console.log(p);
<div>
    <p>ParagraphA</p>
    <p>ParagraphB</p>
</div>
<div class="entry-content">
    <p>Paragraph1</p>
    <p>Paragraph2</p>
    <p>Paragraph3</p>
</div>
<div>
    <p>Paragraph4</p>
    <p>Paragraph5</p>
</div>
like image 34
marmeladze Avatar answered Dec 04 '22 01:12

marmeladze