views:

4745

answers:

3

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

The if condition is what's giving me trouble. 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 }
+6  A: 

This snippet will work:

if ($('#myfav').is(':parent')) {
    // do something
}

Note that the :parent filter also assumes elements with text nodes are parents.

Thus the div elements in <div>some text</div> and <div><span>some text</span></div> will be considered parents but <div></div> is not a parent.

Marve
+1 for the informative explanation, although it didn't work out for me since my code is one of those exceptions where I do have spaces and new lines remnants of old removes. Good info though.
Chris
Yes, I think this answer is more elegant than S Pangborn's. Both are completely legit though.
KyleFarris
+8  A: 
if ( $('#myfav').children().size() > 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.

S Pangborn
Thanks for the answer. This is is what worked for me. I knew I was on the right track with the .children(), but didn't know what was wrong with it. Apparently size could be 0, makes sense.
Chris
+1  A: 

Another option, just for the heck of it would be:

if ( $('#myFav > *').length > 0 ) {
     // do something
}

May actually be the fastest since it strictly uses the Sizzle engine and not necessarily any jQuery, as it were. Could be wrong though. Nevertheless, it works.

KyleFarris
good answer too
Chris