Kalaiyarasan
Kalaiyarasan

Reputation: 13374

have to get the id of each divs under the main div based on class name

Hi in my page i have one main div it is having many child divs. i want to find the each div ids based on the class name i.e.,

<div id="main"> 
 <div id="child1" class="child"> 

</div>
 <div id="child2" class="child"> 

</div>
 <div id="child3" class="child"> 

</div>
</div>

i'm trying to get the id of the each div by using the following script. But it is viewing only the first div id

$("#main").each(function() {
    var val = $(this).find(".child").attr("id");
     alert(val);//displays only child1
 });

Can any one suggest me how can i get the each div ids

Upvotes: 1

Views: 627

Answers (2)

Abhilash
Abhilash

Reputation: 1610

This is another way to do the same thing. Note the use of this.id in place of $(this).attr('id'). Simpler/cleaner to read.

$('#main .child').each( function(){
    alert(this.id);
});

Link to jsbin

Note: It is preferred to use .prop() rather than .attr() in the latest versions of jQuery

Upvotes: 1

rahul
rahul

Reputation: 7663

you are looping through main div instead of it's child div's that's why its' only getting the first child div id

you can do it like this

$.each($("#main .child"),function()
{
   alert($(this).attr('id'));
});

DEMO

Upvotes: 6

Related Questions