1

You can do like if($('.div').find('.someelem').length == 0 .. to check whether .someelem is available inside the div,

but what if I want to check for any element? I don't know what is the class within.

<div>
</div>

^ Check above div contain something or not.

Elton Jamie
  • 586
  • 6
  • 17

1 Answers1

2

A faster way to do it is using .find() cause it will not trigger the somewhat expensive jQuery's Sizzle Selector Library:

if( !$(".div").find(">")[0] ){
    // Maybe has text, but has absolutely no children Elements.
}

If you want to be more specific about your selectors, instead of using ">" (any immediate child) you can use "div" aswell, to restrict your search to DIV Elements only.


You can also check with "if is empty"

$(".div:empty").someMethodYouWant(); // Do some stuff on empty elements. (Really empty)

or

if( $(".div").is(":empty")  ){
    // Has no elements and no text
}

note that the above will yield false if you have just some text (means it's not empty).

If you rather want to go for immediate children > elements

if( !$(".div:has(>)").length ){
    // Maybe has text, but has absolutely no children Elements.
}

or also:

if( !$(".div:has(>)")[0] ){
    // Maybe has text, but has absolutely no children Elements.
}

or even simpler:

if( !$(".div >")[0] ){
    // Maybe has text, but has absolutely no children Elements.
}
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 1
    holy cow great answer! – Elton Jamie Mar 23 '15 at 02:08
  • You can also use [$(selector).children()](https://api.jquery.com/children/) to simply see if an element has any children but it checks only for **immediate children**. [Anyway find() is faster than children()](http://stackoverflow.com/questions/648004/what-is-fastest-children-or-find-in-jquery). – Nipuna Mar 23 '15 at 02:28