Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element has any children?

Tags:

html

jquery

dom

I am trying to remove an element from the DOM if it does not contain any elements.

Here is what I tried:

var numChildren = 0;
$("#messages").children().each(function () {
    numChildren += 1;
});
if (numChildren <= 0) {
    $("#messages").slideUp("normal", function () { $(this).remove(); });
}
like image 452
Alex Hope O'Connor Avatar asked Jun 12 '11 08:06

Alex Hope O'Connor


Video Answer


1 Answers

var messages = $('#messages');
if (messages.children().length < 1) {
    messages.slideUp('normal', function () { $(this).remove(); });
}    

Don't forget though that this will remove the messages div from the DOM.

like image 69
Darin Dimitrov Avatar answered Oct 22 '22 01:10

Darin Dimitrov