• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / jQuery / jQuery hasClass – How to Check if an Element Has a Certain Class

jQuery hasClass – How to Check if an Element Has a Certain Class

March 22, 2022 Leave a Comment

We can use the jQuery hasClass method to check and see if any element has a specified class. The hasClass method will return true if the class is found, or false if it is not.

$('#div1').hasClass('sub-div');

Let’s say I have the following HTML:

<div id="div1">
  <p>This is some text.</p>
  <p class="special-class">This is some text.</p>
  <p>This is some text.</p>
  <p>This is some text.</p>
  <p>This is some text.</p>
</div>

If we want to check the div, #div1, to see if any of the paragraphs in it have a class called “special-class”, we can do the following code:

if ($('#div1 p').hasClass('special-class')){
  $('#div1').css('background','green');
}

As you can see, if a paragraph in the div does contain that class, we will change the background color of the div to green.

If you are using WordPress, don’t forget to change the $ to jQuery as below:

if (jQuery('#div1 p').hasClass('special-class')){
  jQuery('#div1').css('background','green');
}

Let’s take a look at a dynamic example of using the jQuery hasClass() method.

Using jQuery hasClass Method to Add Styles Based on the Content of a Div

In this example, we will use a random number generator to generate 3 numbers. For the HTML setup for this example, all we need is an empty div to start with, a results div, and a button that will run a function when clicked on.

Here is the simple HTML setup:

<div id="numbers">
  <div id="random-numbers"></div>
  <div id="results"></div>
  <p>Click the button below to generate 3 random numbers and see if any are even.</p>
  <div id="click-me">Generate numbers and check</div>
</div>

In the first part of the JavaScript code, we will generate a random number from 1 to 20.

Once we generate the numbers, we will check if each is even number or odd. We will then append the new number with a new span tag and a class of either even or odd, to our div, #numbers.

Finally, we will check if our #numbers div has any classes that are even, meaning that one of the 3 numbers is even. If it does, we will note that there is an even number in the list. If not, we mark that there are none. We will do this with the help of the text() method.

This example is just a simple way to show the power of the jQuery hasClass() method.

Here is the JavaScript and jQuery code:

$('#click-me').click(function(){
  //First, clear div, random-numbers
  $('#random-numbers').text('');
  //Generate 3 random number between 1 and 20
  for (var i=0; i < 3; i++){
    var newNumber = Math.round(Math.random() * 20);
    //Check if new number is even
    if ((newNumber % 2) == 0) {
      //Create a new span with class even and add it to the div
      $('<span style="display: inline-block; margin-right:10px;" class="even">' + newNumber + '</span>').appendTo("#random-numbers");
    } else {
      $('<span style="display: inline-block; margin-right:10px;">' + newNumber + '</span>').appendTo("#random-numbers");
    }
  }
  //Once we have added all the numbers, we can check if there are any even numbers
  if ($('#random-numbers span').hasClass('even')){
    $('#results').text('The list of numbers above HAS an even number in it.');
  } else {
    $('#results').text('The list of numbers above Does NOT Have an even number in it.');
  }
});

The final code and output for this example is below:

Code Output:

Click the button below to generate 3 random numbers and see if any are even.

Generate numbers and check

Full Code:

<div id="numbers">
  <div id="random-numbers"></div>
  <div id="results"></div>
  <p>Click the button below to generate 3 random numbers and see if any are even.</p>
  <div id="click-me">Generate numbers and check</div>
</div>

<script>

$('#click-me').click(function(){
  //First, clear div, random-numbers
  $('#random-numbers').text('');
  //Generate 3 random number between 1 and 20
  for (var i=0; i < 3; i++){
    var newNumber = Math.round(Math.random() * 20);
    //Check if new number is even
    if ((newNumber % 2) == 0) {
      //Create a new span with class even and add it to the div
      $('<span style="display: inline-block; margin-right:10px;" class="even">' + newNumber + '</span>').appendTo("#random-numbers");
    } else {
      $('<span style="display: inline-block; margin-right:10px;">' + newNumber + '</span>').appendTo("#random-numbers");
    }
  }
  //Once we have added all the numbers, we can check if there are any even numbers
  if ($('#random-numbers span').hasClass('even')){
    $('#results').text('The list of numbers above HAS an even number in it.');
  } else {
    $('#results').text('The list of numbers above Does NOT Have an even number in it.');
  }
});

</script>

Hopefully this article has been useful for you to understand how to use the jQuery hasClass method.

Other Articles You'll Also Like:

  • 1.  Using jQuery to Remove Attribute from HTML Element
  • 2.  jQuery has – Check if an Element Has Other Elements
  • 3.  jQuery focusin – Changing the Background Color with the focusin() Method
  • 4.  Resizing an Image Using jQuery
  • 5.  How to Clear an Input Field Using jQuery
  • 6.  Using jQuery to Move Element After Another
  • 7.  Using jQuery to Get Value of Select On Change
  • 8.  How to Filter a List of Divs with a Text Input Bar Using Javascript
  • 9.  Using jQuery to Append Text to textarea Field
  • 10.  Using jQuery to Get Text Length

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy