JavaScript
Article

jQuery Check if Element has Class Attached

By Sam Deering

jQuery code snippet to check whether a web page element has a specific css class attached. Could be used to check if the element needs additional formatting or if you want to protect certain page elements. To do this we can use the jQuery hasClass() function or jQuery is() function.

$("div").click(function(){
	if ( $(this).hasClass("protected") ) {
		//do something it does have the protected class!
		alert("i have the protected class");
	}
});


OR

$("div").click(function(){
   if ( $('#myDiv').is('.pretty.awesome') ) {
	   //do something it does have the protected class!
	   alert("i have the pretty and awesome classes");
   }
});

Note: that this method allows you to test for other things as well. IE – Check if an element is hidden.

if ( $('#myDiv').is(':hidden') ) {
   //do something I am hidden!
   alert("i am hidden!");
}

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.