estellechvl
estellechvl

Reputation: 335

jQuery: Set display:none if an element has no children

So I have a aside element that contains some div. The div are generated with PHP, and sometimes the aside has no div children.

What I want is to hide this aside parent when it doesnt have any div children.

So far i've tried different solutions has

if($('aside').length)
    {
        if($('aside').find('*').length == 0)
        {
            $('aside').hide();
        }
    }

obv not working.

the php looks like that

<aside>
    <div class="children1"></div>
    <div class="children2"></div>
</aside>

Upvotes: 0

Views: 1339

Answers (4)

DooDoo
DooDoo

Reputation: 13457

if($('aside').children(":first").length == 0)
{
     $('aside').hide();
}

Upvotes: 0

GordonM
GordonM

Reputation: 31740

The following will hide all aside tags that don't contain anything at all.

$('aside:empty').hide();

However it doesn't work if it contains whitespace, or empty child nodes

After a lot of fiddling around I figured out that if you want to do this client-side then your best option is to iterate over all the asides and determine which ones don't contain anything meaningful. The following code seems to do the job adequately.

$('aside').each (function (index, elem) {
    elem = $(elem);
    if ('' == elem.text ().trim ()) {
        elem.hide ();
    }
});

JSFiddle here.

However, it's probably better to just not include the at all in the markup when generating it server side if there's nothing to go in it. It'll reduce the amount of data you need to send (slightly) and be rendered correctly regardless of whether the user has javascript enabled.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382177

You can use this to hide all aside elements without children :

$('aside').filter(function(){ return !$(this).children().length }).hide()

Demonstration

Note that it's usually easy to test in PHP if you have elements to write and in the opposite case, simply not write the aside element. Instead of sending HTML and erase it client side, I'd rather not send it.

Upvotes: 2

thewulf00
thewulf00

Reputation: 67

Pay attention to the running time of the script

$(document).ready(function(){
    if ( !$('aside').children().length )
        $('aside').hide();
};

Additionally you shouldn't refer to the element by its TagType ('aside'). Use identifiers or classes.

Upvotes: -1

Related Questions