Anjali
Anjali

Reputation: 329

select all div by class name inside of the div

how to select div p and p2 inside of r only through query selector , i dont want to select div p and p2if its not inside of classr

<div>
<div class="r"><div class="p"></div><div class="p2"></div></div> //want to select this , i know it can accessed with tad name div
</div>

<div class="r"><div class="p"></div><div class="p2"></div></div> // I dont want to select this if the parent div is body

CSS

.p,.p2{
height:50px;
width:50px;
background-color:orange
}

the javascript which ive tried is , is this correct how to achieve

c = document.querySelectorAll( ' x >.r' ) // where x is the parent tag tagName of r 

Upvotes: 1

Views: 1818

Answers (3)

RobG
RobG

Reputation: 147413

If you want to select by class, then you can do:

document.querySelectorAll('div div.r .p, div div.r .p2');

Note that these selectors work anywhere (e.g. as a style rule), there is no need for additional scripting.

e.g.

window.onload = function() {
  var x = document.querySelectorAll('div div.r .p, div div.r .p2');
  console.log('Found: ' + x.length);
};
<!-- Descendants of a div -->
<div>
  <div class="r">
    <div class="p">p below div and div.r</div>
    <div class="p2">p2 below div and div.r</div>
  </div>
</div>

<!-- Descendants of body -->
<div class="r">
  <div class="p">p below body and div.r</div>
  <div class="p2">p2 below body and div.r</div>
</div>

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

So based on your requirement, you want to just select the first child's descendants,

Then just use :first-child selector.

var firstChild = document.querySelector(".r:first-child");
var descendant = firstChild.querySelectorAll(".p, .p2");

Array.from(descendant).forEach(function(itm){
  itm.style.backgroundColor = "red";
});

DEMO

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

You can use

c = document.querySelectorAll(".r .p, .r .p2");

The comma separates selectors, just like in CSS, and a b means "b inside a".

Upvotes: 2

Related Questions