JQuery: iterating 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, but also would like to know if I am in a or b. using the basic jquery syntax, each of which cannot find this.

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

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

+8
source
if($(this).parent().hasClass('a'))

And the same for b, it should work.

+1
source

, :

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

$('.b .m').each(function(index) {
    // now I'm on .b items
});
+1
$('.m').each(function(index) {
    this.parentNode.getAttribute( "class" );
});
0

, .a

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

.closest:

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

, , 'a' 'b'

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

, var "a" "b"

0

All Articles