Botond Vajna
Botond Vajna

Reputation: 1521

Javascript querySelectorAll elements that have a parent element with specific class

let say I have:

<div class = "testimonials-wrapper">
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
</div>

<blockquote>...</blockquote>

<div class = "testimonials-wrapper">
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
</div>

How can I select the <blockquote> elements, but only that are inside the testimonials-wrapper

tryed: document.querySelectorAll(".testimonials-wrapper .blocquote"); but no luck

Upvotes: 2

Views: 2510

Answers (3)

Quentin
Quentin

Reputation: 943569

All elements that have a parent element with specific class

OK, so "All elements" is the universal selector:

*

"with a parent element" is the child combinator

... > *

And "with specific class" is the class selector:

.testimonials-wrapper > *

.testimonials-wrapper .blocquote

That selects descendants of testimonials-wrapper not children, you misspelt blockquote, and you used a class selector instead of a type selector.

Upvotes: 1

Nithish
Nithish

Reputation: 6009

You can use below query to get all the blockquotes inside testimonials-wrapper class

document.querySelectorAll(".testimonials-wrapper blockquote")

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

You can simply use:

document.querySelectorAll(".testimonials-wrapper blockquote")

This will only return all the <blockquote> elements, but only that are inside the testimonials-wrapper class.

var blockquotes = document.querySelectorAll(".testimonials-wrapper blockquote");
console.log( blockquotes.length )
<div class = "testimonials-wrapper">
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
</div>

<blockquote>...</blockquote>

<div class = "testimonials-wrapper">
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
   <blockquote>...</blockquote>
</div>

You can see in this demo blockquotes.length returned is 6 instead of 7 as it ignores the <blockquote> in the middle using this selector.

Upvotes: 3

Related Questions