jquery if div id has children

Chris picture Chris · Oct 6, 2009 · Viewed 271.8k times · Source

This if-condition is what's giving me trouble:

if (div id=myfav has children) {
   do something
} else {
   do something else 
}

I tried all the following:

if ( $('#myfav:hasChildren') ) { do something }
if ( $('#myfav').children() ) { do something }
if ( $('#myfav:empty') ) { do something }
if ( $('#myfav:not(:has(*))') ) { do something }

Answer

S Pangborn picture S Pangborn · Oct 6, 2009
if ( $('#myfav').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.