Skip to main content

jQuery Check if Element has Class Attached

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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!");
}

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.