using jQuery to determine if children of a div have a css class

325
November 23, 2016, at 4:03 PM

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?

Answer 1

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

Answer 2

use

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

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

Answer 3
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.

Answer 4

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.

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

Should do the job :-)

Answer 6

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")) {
  ...
}
READ ALSO
Set a delay in ajax call

Set a delay in ajax call

I am trying to add a small delay (2 sec) between the loader icon and the success with the data as html. .

311
Html/php: how to include a php file when only a tab is clicked using php & html only?

Html/php: how to include a php file when only a tab is clicked using php & html only?

What I'm trying to do is including multiple php files in my page put I want to load php files only when I click the related tab.

241
How to print (in the screen) all JS code required by an iframe with external url

How to print (in the screen) all JS code required by an iframe with external url

I want to show in an iframe a webpage (an external url), and then show all the code JS requested by this iframe in a textarea. .

366
jquery $.each vs for loop (with async content)

jquery $.each vs for loop (with async content)

What is the main difference between:.

345