jQuery hasClass - Check if an element has a particular class

Learn about the jQuery hasClass function.

The jQuery hasClass function is pretty straightforward really. There might be times when you want to check an element on a page and determine whether or not it has a particular CSS class. That’s where the jQuery hasClass function comes in - just select the element you want to check and call the function.

jQuery hasClass - Example

Imagine you have the following snippet of HTML markup:

 
  • Home
  • Blog
  • About
  • Contact

It’s the kind of thing you might expect on a menu or navigation bar of a web page. You’ll see that one of

  • tags has the class of active applied. This could be used to identify the page that is currently being viewed by the user and some different styling is applied accordingly. Now, if you want to work out which page is active in JavaScript (and perform some action using that information) you can use the jQuery hasClass function to find out which page is active. So let’s say you want to work out if your user is currently on the home page. You could use the jQuery hasClass function like this:

    $(function(){
        if($('#home').hasClass('active')){
            console.log("You're on the home page.");
        }
    });

    So, as you can see the jQuery hasClass function returns a boolean - either true or false. That’s handy as you can just plug it into an if statement like in the above example. If you did want to get the string representation of the result of the hasClass function you can always chain the toString() function on top:

    $(function(){
        var isHome = $('#home').hasClass('active').toString();
        console.log("Home page?", isHome);
    });

    Conclusion

    There are a few other examples I can think of where the jQuery hasClass function might be useful:

    • You want to pick out a number of images in a gallery (that has a specific class applied)
    • You want to check if a selection of paragraphs have a style applied to them
    • You are using a custom checkbox (e.g. on a div element) and you want to check if it is selected

    These can be achieved by pretty much copying the code in the above examples, just remember that the jQuery hasClass function can be plugged straight in to an if statement as it returns a boolean value. Got any other examples of why / how you have used the jQuery hasClass function? Let me know in the comments below.