clamp
clamp

Reputation: 34036

jQuery: iterate over nested elements using each

i have this basic html structure:

<div class=a>
  <div class=m></div>
  <div class=m></div>
</div>
<div class=b>
  <div class=m></div>
  <div class=m></div>
</div>

now i want to iterate over all m's but also would like to know if i am in a or b. using basic jquery syntax each i fail to do find this out.

$('.m').each(function(index) {
    // how do i know if this m is part of a or b ?
});

Upvotes: 5

Views: 983

Answers (7)

Brian Glaz
Brian Glaz

Reputation: 15696

You can check the class of the parent element inside your function to identify if you are in 'a' or 'b'

$('.m').each(function() {
     var parentClass = $(this).parent().attr('class');
});

So, the parentClass var should have a value of either 'a' or 'b'

Upvotes: 0

Blindy
Blindy

Reputation: 67544

If you care, then I'd separate the selectors like this:

$('.a .m').each(function(index) {
    // now I'm on .a items
});

$('.b .m').each(function(index) {
    // now I'm on .b items
});

Upvotes: 1

Kevin B
Kevin B

Reputation: 95058

You could use the .closest method:

var $this = $(this);
if ($this.closest("a").length === 1) {
    alert("I'm in an a div");
}
else {
    alert("I'm in a b div");
}   

Upvotes: 0

Whiskas
Whiskas

Reputation: 352

if($(this).parent().hasClass('a'))

And same for b, it should work.

Upvotes: 1

Jamiec
Jamiec

Reputation: 136239

For example, check the parent is .a

if($(this).parent().is('.a'))

Upvotes: 0

mark_dj
mark_dj

Reputation: 994

$(this).parent().hasClass("a") or $(this).parent().hasClass("b")

Upvotes: 8

KeatsKelleher
KeatsKelleher

Reputation: 10191

$('.m').each(function(index) {
    this.parentNode.getAttribute( "class" );
});

Upvotes: 0

Related Questions