Check if a class `active` exist on element with jquery
Check if a class active
exist on an li
with a class menu
For example
<li cla开发者_C百科ss="menu active">something...</li>
I think you want to use hasClass()
$('li.menu').hasClass('active');
You can retrieve all elements having the 'active' class using the following:
$('.active')
Checking wether or not there are any would, i belief, be with
if($('.active').length > 0)
{
// code
}
You can use the hasClass
method, eg.
$('li.menu').hasClass('active') // true|false
Or if you want to select it in one go, you can use:
$('li.menu.active')
$('li.menu.active')
is the simplest way. This will return all elements with both classes.
Or an already answered jQuery hasClass() - check for more than one class
Pure JavaScript answer:
document.querySelector('.menu').classList.contains('active');
Might help someone someday.
if($('selector').hasClass('active')){ }
i think this will check if the selector hasClass active ...
$(document).ready(function()
{
changeColor = $(.active).css("color","any color");
if($(".classname").hasClass('active')) {
$(this).eq(changeColor);
}
});
use the hasClass jQuery method
If Condition to check, currently class active or not
$('#next').click(function(){
if($('p:last').hasClass('active'){
$('.active').removeClass();
}else{
$('.active').addClass();
}
});
i wrote a helper method to help me go through all my selected elements and remove the active class.
function removeClassFromElem(classSelect, classToRemove){
$(classSelect).each(function(){
var currElem=$(this);
if(currElem.hasClass(classToRemove)){
currElem.removeClass(classToRemove);
}
});
}
//usage
removeClassFromElem('.someclass', 'active');
精彩评论