I\'m trying to remove a specific div if a separate div is empty. Here\'s what I\'m using:
$(document).ready(function () {
if (\'#leftmenu:empty\') {
Try this:
$(document).ready(function() {
if ($('#leftmenu').html() === "") {
$('#menuTitleWrapper').remove();
$('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
$('#PageContent').css({'top' : '30px', 'position' : 'relative'});
}
});
It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).
I've encountered this today and the accepted answers did not work for me. Here is how I did it.
if( $('#div-id *').length === 0 ) {
// your code here...
}
My solution checks if there are any elements inside the div so it would still mark the div empty if there is only text inside it.
It depends what you mean by empty.
To check if there is no text (this allows child elements that are empty themselves):
if ($('#leftmenu').text() == '')
To check if there are no child elements or text:
if ($('#leftmenu').contents().length == 0)
Or,
if ($('#leftmenu').html() == '')
If you want a quick demo how you check for empty divs I'd suggest you to try this link:
http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/
Below you have some short examples:
Using CSS
If your div is empty without anything even no white-space, you can use CSS:
.someDiv:empty {
display: none;
}
Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y
.someDiv:empty ~ .anotherDiv {
display: none;
}
Using jQuery
Checking text length of element with text() function
if ( $('#leftmenu').text().length == 0 ) {
// length of text is 0
}
Check if element has any children tags inside
if ( $('#leftmenu').children().length == 0 ) {
// div has no other tags inside it
}
Check for empty elements if they have white-space
if ( $.trim( $('.someDiv').text() ).length == 0 ) {
// white-space trimmed, div is empty
}