How do I test whether an element has a particular class?

January 19, 2010 | Filed Under JQuery | Comments Off

* You can use the is() method along with an appropriate selector

if ( $(‘#myDiv’).is(‘.pretty’) )
$(‘#myDiv’).show();

Note that this method allows you to  test for other things as well. For example, you can test whether an element is hidden (by using the custom :hidden selector):

if ( $(‘#myDiv’).is(‘:hidden’) )
$(‘#myDiv’).show();

* Note  also that hasClass has been added as of version 1.2 to handle the most common use of is():

$(“div”).click(function(){
if ( $(this).hasClass(“protected”) )
$(this)
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: 0 });
});

Comments

Comments are closed.

© PHPInterviewQuestion.com 2009 - 2012

eXTReMe Tracker