0

On one of my web pages I'm currently checking whether a css class isn't being used, like so:

if (!$('*').hasClass("my-special-class")) {

The above works but it's checking every element on the page. In fact, I only need to check within a particular div (id = 'mydiv') and its child elements, but am not quite sure what sort of selector to use, and would welcome a suggestion?

6 Answers 6

3

All you need to do is use the selector itself to compare in an if statement

if($('.my-special-class').length > 0){
    //element with this class exists - do something
}

This will search the DOM for any element with the class my-special-class. If it cannot find that element, then the length is returned as 0

Alternatively you can modify your selector if you want to find it within a certain element -

if($('#myDiv .my-special-class').length > 0){
    //element exists in #myDiv - do something
}

This selector works the same way that any CSS selector works, any children of myDiv with the class my-special-class will be selected

Sign up to request clarification or add additional context in comments.

Comments

1

use

$('#myID').find(".my-special-class").length

It will return 0, if there are no elements with that class inside that parent div.

Comments

1
if ( $('#yourIDorClass').children().length > 0 ) {
     // do something
}

This should work. The children() function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.

Comments

1

you have to use like this

$('#mydiv *').hasClass("my-special-class")

It will return true if the class is being used by any of the child elements of mydiv,false if not used.

Comments

1
$('#myDiv .my-special-class').length

Should do the job :-)

Comments

0

The reason that it is checking everything on your HTML page for that class is because you are using '*' in your jQuery selector.

If you want to target a specific div with jQuery just alter your code to look like:

if (!$('#myDiv').hasClass("my-special-class")) {
  ...
}

1 Comment

it will only check if myDiv has class my-special-class but not for all the child elements having the my-special-class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.