6

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?

2 Answers 2

19

Specify the div's class:

document.querySelectorAll('div.entry-content > p');
4

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.