Emil
Emil

Reputation: 423

How find nested div with same class name in jquery?

I want to find all div with specific class name. May be one div have nested div with parent div class name. suppose this example:

<div class="myForm">
   <div class ="myDiv">
     <div class ="myDiv">
     </div> 
   </div> 
   <div class ="myDiv">
     <div class ="myDiv">
     </div> 
   </div> 
</div> 

In fact I want to find all div with "myDiv" class name and also recognize nested div. In the above example, there are 2 to 4 of them are nesting.

Upvotes: 2

Views: 2957

Answers (5)

Himesh Aadeshara
Himesh Aadeshara

Reputation: 2121

you can use the > operator in element selector like

$('.myForm > .myDiv').child('.myDiv');

Upvotes: 0

JDupont
JDupont

Reputation: 1352

I think an answer would also mention that having redundant class names for children is bad practice and should be avoided.

<div class="myForm">
   <div class ="myDiv">
     <div>
     </div> 
   </div> 
   <div class ="myDiv">
     <div>
     </div> 
   </div> 
</div>

Query children like, $('.myDiv, .myDiv > div') or make separate class names for nested divs.

Upvotes: 0

Rohit Arora
Rohit Arora

Reputation: 2252

Try this:

For all myDiv's:

$('.myDiv')

For All nested myDiv's only:

$('.myDiv .myDiv')

For Only main 'myDiv's' excluding nested myDiv's:

$(".myDiv").not(".myDiv .myDiv")

Check Out this DEMO

Upvotes: 0

Zohaib Waqar
Zohaib Waqar

Reputation: 1239

Try this

var element = $(".myForm").find(".myDiv");

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115232

You can use >, direct children selector

$('.myForm > .myDiv')

or

$('.myDiv').parent('.mydiv')

or

$('.myForm').children('.myDiv')

Upvotes: 1

Related Questions