1

I have this line of HTML:

<li class="col-xs-6 col-sm-6 col-md-2 filter active" data-filter=".office">

And i want to check if the ".filter" has class ".active", if it has active class then i need to get its data attribute. I tried like this, but it alerts undefined

if($(".filter").hasClass("active")) {

    var activeFilter = $(this).attr("data-filter");
    alert(activeFilter);
}

What I'm doing wrong?

Viktor
  • 1,036
  • 1
  • 12
  • 25

1 Answers1

8

Where this not refers to the element which may refer to window object or any other context. To make it work, cache the element reference(jQuery object) and do the rest on the cached object.

var $ele = $(".filter");
if($ele.hasClass("active")) {
    var activeFilter = $ele.attr("data-filter");
    alert(activeFilter);
}

var $ele = $(".filter");
if ($ele.hasClass("active")) {
  var activeFilter = $ele.attr("data-filter");
  alert(activeFilter);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="col-xs-6 col-sm-6 col-md-2 filter active" data-filter=".office"></li>
</ul>

Or in case there are multiple elements then use each() method and you can refer the current element using this keyword within the callback.

$(".filter").each(function(){
  if($(this).hasClass("active")) {
    var activeFilter = $(this).attr("data-filter");
    alert(activeFilter);
  }
})

$(".filter").each(function() {
  if ($(this).hasClass("active")) {
    var activeFilter = $(this).attr("data-filter");
    alert(activeFilter);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="col-xs-6 col-sm-6 col-md-2 filter active" data-filter=".office"></li>
</ul>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188