We can use the jQuery has method to check and retrieve any elements that have another element or specified class.
$('#div1').has('sub-div');
Let’s say I have the following HTML:
This is some text.
This is some text.
This is some text.
This is some text.
This is some text.
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').has('special-class')){
$('#div1').css('background','green');
}
As you can see, if 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').has('special-class')){
jQuery('#div1').css('background','green');
}
Using the jQuery has Method to Add Styles Based on the Content of a Div
In this example, we will check if a div has a paragraph with a specific class. If it does, we will change the background color of the div.
Here is the simple HTML setup:
This is some text.
This is some text.
This is some text.
This is some text.
This is some text.
Check class
In the JavaScript part of this example, we first run a function when the user clicks the check button.
In our function, we simply check if the class, special-class, exists in one of the paragraphs in the div, #div1.
To do this we will use the jQuery has() method.
Since the jQuery has() method returns each element that has the specified class, which will be #div1 in this case, we can then change the background color of it right after the has() method call.
Here is the JavaScript and jQuery code:
$('#click-me').click(function(){
$("#div1").has(".special-class").css("background", "#7bbfa2");
});
The final code and output for this example is below:
Code Output:
This is some text.
This is some text.
This is some text.
This is some text.
This is some text.
Full Code:
This is some text.
This is some text.
This is some text.
This is some text.
This is some text.
Check class
Hopefully this article has been useful for you to understand how to use the jQuery has method.