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!");
}
Tags: jquery attach class to element, jquery check element class, jquery element class, jQuery hasClass(), jQuery hasClass() function
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


No Reader comments

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.