Reputation: 14209
I have the following JS:
if ( $("#secretContent").children().length == 0) {
$("#seemore").hide();
}
and here is a jsFiddle demonstrating my questions. I have the intention of hiding the div with id "seemore" when the div with id "secretContent" has no children/contents.
Any help would be much appreciated. Thanks in advance!
Upvotes: 2
Views: 1485
Reputation: 30099
Probably want to change you "greater than" to an equal:
if ( $("#secretContent").children().length == 0) {
$("#seemore").hide();
}
As Vega suggests, if you care about text nodes, and not strictly children HTML elements, then you need to use contents()
in place of children
:
if ( $("#secretContent").contents().length == 0) {
$("#seemore").hide();
}
Here is a demo showing both:
http://jsfiddle.net/jtbowden/NASQn/
Note! It should be noted that .contents()
counts any text inside of the div
.
This:
<div>
</div>
and this:
<div> </div>
Are both considered not empty because the first has a newline, and the second has a space, which are both considered text nodes. The only thing that is considered empty when using .contents()
is this:
<div></div>
If you want to account for this, you need to check for no children()
and then see if the remaining text is only whitespace:
if ( $("#secretContent").children().length == 0) {
if( $("#secretContent").text().match(/^\s*$/) ) {
$("#seemore").hide();
}
}
Demo: http://jsfiddle.net/jtbowden/4xtME/
Upvotes: 4
Reputation: 2812
This is doing the trick http://jsfiddle.net/chepe263/9Jmug/1/
if ( $("#secretContent").children().length < 1) {
$("#seemore").hide();
}
in the fiddle it shows the content because it has an aditional div inside secretContent
Upvotes: 1
Reputation: 79830
I think you should use .contents
instead of .children
incase if you want to check for text content too. Also changed the >
to ==
. Try and let me know,
if ( $("#secretContent").contents().length == 0) {
$("#seemore").hide();
}
Upvotes: 1
Reputation: 324600
So... You want to replace that > 0
with == 0
, I think.
Upvotes: 4