jkj2000
jkj2000

Reputation: 1593

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

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?

Upvotes: 0

Views: 5616

Answers (6)

Ronen Cypis
Ronen Cypis

Reputation: 21470

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

Should do the job :-)

Upvotes: 1

Tyler Reckart
Tyler Reckart

Reputation: 31

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")) {
  ...
}

Upvotes: 0

Jayababu
Jayababu

Reputation: 1621

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.

Upvotes: 1

Adjit
Adjit

Reputation: 10305

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

Upvotes: 3

youzdev
youzdev

Reputation: 9

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.

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

use

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

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

Upvotes: 1

Related Questions