Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find if an element contains a specific class with jQuery?

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>
like image 503
Clinton Jooooones Avatar asked Jan 15 '12 01:01

Clinton Jooooones


People also ask

How to check an element contains a class using jQuery?

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.

How to check if a selected element contains a specified class?

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:

How to check if a class exists or not in 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. This can be used to check for multiple classes.

How do I test if an element has a particular class?

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.


1 Answers

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)
like image 149
Adam Rackis Avatar answered Oct 01 '22 11:10

Adam Rackis