I need to check if an element contains a certain child class using JQUERY.
I tried:
if ($('#myElement').has('.myClass')) {
do work son
}
Didn't work.
My html code is laid out like this:
<div id="myElement">
<img>
<span>something</span>
<span class="myClass">Hello</span>
</div>
How to check an element contains a class using jQuery? Method 1: Using hasClass () method: The hasClass () is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not.
The jQuery .hasClass () method checks if a selected element contains a specified class name or not. The hasClass () method returns true if the class assigned to the element and return false if the class name is not assigned to that element. Now see the jQuery code below:
Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not. This can be used to check for multiple classes.
How do I test whether an element has a particular class? .hasClass () (added in version 1.2) handles this common use case: You can also use the .is () method along with an appropriate selector for more advanced matching: Note that this method allows you to test for other things as well.
The easiest way would be to search for .myClass
as a child of #myElement
:
if($('#myElement .myClass')).length > 0)
If you only want first level children, you'd use >
if($('#myElement > .myClass')).length > 0)
Another way would be passing a selector to find
and checking for any results:
if($('#myElement').find('.myClass').length > 0)
Or for first level children only:
if($('#myElement').children('.myClass').length > 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With