235

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 }
John Slegers
  • 45,213
  • 22
  • 199
  • 169
Chris
  • 8,736
  • 18
  • 49
  • 56

7 Answers7

508
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.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
S Pangborn
  • 12,593
  • 6
  • 24
  • 24
  • 1
    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 Oct 06 '09 at 18:57
  • 2
    If you add a selector to children, you can also check if an element has children that match a particular selector, like if you want to see if an element has a child of a particular class. – Muhd May 05 '11 at 03:43
  • 12
    minor issue. don't mean to nitpick but `children().length` should be called instead of size() per jQuery docs here: http://api.jquery.com/size – Brian Chavez May 07 '11 at 05:06
  • 4
    And what if the node only contains text!? – botenvouwer Aug 09 '13 at 09:43
  • 1
    @sirwilliam The node will return with 0 length. – Meki Sep 14 '15 at 12:50
58

This snippet will determine if the element has children using the :parent selector:

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

Note that :parent also considers an element with one or more text nodes to be a parent.

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

dcharles
  • 4,822
  • 2
  • 32
  • 29
  • +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 Oct 06 '09 at 18:56
  • 2
    Yes, I think this answer is more elegant than S Pangborn's. Both are completely legit though. – KyleFarris Oct 06 '09 at 18:58
  • I know this is old, but would `($('#myfav :parent').length > 0)` be faster? I find yours more readable so it probably isn't worth the trade off in most situations. – Milo LaMar Jan 12 '12 at 03:36
  • 1
    @Milo LaMar, I'd suspect there isn't much of a performance difference, but the only way to be sure is to try it! Also, you'd have to remove the space between `#myfav` and `:parent` in your example, otherwise the selector isn't the same as what my answer would provide. – dcharles Jan 12 '12 at 19:11
  • 3
    A very small amount of reading answered enough for me. Taken from http://api.jquery.com/parent-selector/ `Additional Notes: Because :parent is a jQuery extension and not part of the CSS specification, queries using :parent cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :parent to select elements, first select the elements using a pure CSS selector, then use .filter(":parent").` – Milo LaMar Jan 13 '12 at 02:54
  • 6
    performance test results in 0.002s - i prefer this way, because it's best readable... – dtrunk Mar 01 '12 at 10:15
  • 1
    I'm confused, isn't this the best answer? – Andrei Cristian Prodan Oct 01 '12 at 13:30
  • **Important note:** the `:parent` selector takes into account any text nodes -- ***which includes white space*** -- so `.is(':parent')` is true if you had a single space, like `
    `.
    – jbyrd Feb 11 '19 at 17:42
49

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
  • 17,274
  • 5
  • 40
  • 40
17

You can also check whether div has specific children or not,

if($('#myDiv').has('select').length>0)
{
   // Do something here.
   console.log("you can log here");

}
Rakesh Chaudhari
  • 3,310
  • 1
  • 27
  • 25
16

There's actually quite a simple native method for this:

if( $('#myfav')[0].hasChildNodes() ) { ... }

Note that this also includes simple text nodes, so it will be true for a <div>text</div>.

Simon
  • 7,182
  • 2
  • 26
  • 42
  • `$(...)[0] is undefined` this may happen if `#myfav` is not found. I'd test the existence of the first matched element prior to apply that condition, i.e.: `$('#myfav')[0] && $('#myfav')[0].hasChildNodes()`. – CPHPython Sep 11 '18 at 13:19
16

and if you want to check div has a perticular children(say <p> use:

if ($('#myfav').children('p').length > 0) {
     // do something
}
suhailvs
  • 20,182
  • 14
  • 100
  • 98
8

The jQuery way

In jQuery, you can use $('#id').children().length > 0 to test if an element has children.

Demo

var test1 = $('#test');
var test2 = $('#test2');

if(test1.children().length > 0) {
    test1.addClass('success');
} else {
    test1.addClass('failure');
}

if(test2.children().length > 0) {
    test2.addClass('success');
} else {
    test2.addClass('failure');
}
.success {
    background: #9f9;
}

.failure {
    background: #f99;
}
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<div id="test">
   <span>Children</span>
</div>
<div id="test2">
   No children
</div>

The vanilla JS way

If you don't want to use jQuery, you can use document.getElementById('id').children.length > 0 to test if an element has children.

Demo

var test1 = document.getElementById('test');
var test2 = document.getElementById('test2');

if(test1.children.length > 0) {
    test1.classList.add('success');
} else {
    test1.classList.add('failure');
}

if(test2.children.length > 0) {
    test2.classList.add('success');
} else {
    test2.classList.add('failure');
}
.success {
    background: #9f9;
}

.failure {
    background: #f99;
}
<div id="test">
   <span>Children</span>
</div>
<div id="test2">
   No children
</div>
John Slegers
  • 45,213
  • 22
  • 199
  • 169