0

i cant access clicked object(this) parent's class.. click same elements and different returns?

this is DEMO

HTML

<div class="rows row1">
  <div class="ele">1</div>
  <div class="ele">1</div>
  <div class="ele">1</div>
</div>

<div class="rows row2">
  <div class="ele">2</div>
  <div class="ele">2</div>
  <div class="ele">2</div>
</div>

jQuery

$('.ele').click(function() {

  if ( $(this).parent().hasClass('r1') ) {//way1
    alert('you clicked 1st row element');
  }

  else if ( $(this).parent().hasClass('r2') === true ) {//both way wont work
    alert('you clicked 2nd row element');
  }

});

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86

1 Answers1

4

Because both parent have no r1 or r2 class, that should be row1 and row2:

$('.ele').click(function() {

  if ( $(this).parent().hasClass('row1') ) {
    alert('you clicked 1st row element');
  }

  else if ( $(this).parent().hasClass('row2')) {
    alert('you clicked 2nd row element');
  }

});

demo here

mgraph
  • 15,238
  • 4
  • 41
  • 75