最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - If div has no content hide other div - Stack Overflow

programmeradmin1浏览0评论

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!

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!

Share Improve this question edited Apr 1, 2014 at 21:59 jacktheripper asked Apr 23, 2012 at 16:41 jacktheripperjacktheripper 14.3k12 gold badges60 silver badges93 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

So... You want to replace that > 0 with == 0, I think.

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/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/jtbowden/4xtME/

This is doing the trick http://jsfiddle/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

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();
}​

replace " > 0 " with "== 0"

That should do the trick!

发布评论

评论列表(0)

  1. 暂无评论