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>