131
131

Reputation: 1385

Hide div, without hiding it's nested divs

This is a simple question, but i can't seem to find the answer anywhere on stackoverflow.

I have the following code-snippet:

<div>//The div to be hidden
    <div></div>//I don't want to hide this div
    <div></div>//Nor this one
</div>

The reason why i wanna do this is because, when i hide the divs, i hide them using their tagname, but when i show them, i use their classname. Therefore the innerdivs or the "nested divs" doesn't show up again.

EX:

Before:

<div>
    <div></div>
    <div></div>
</div>
<div></div>
<div>
    <div></div>
    <div></div>
</div>

After:

<div style="display:none;">
    <div></div>
    <div></div>
</div>
<div style="display:none;"></div>
<div style="display:none;">
    <div></div>
    <div></div>
</div>

Upvotes: 1

Views: 2129

Answers (2)

Josh
Josh

Reputation: 1281

I'm assuming that the code provided is inside another element. I'm going to call this div#root

<div id="root">
    <div>
        <div></div>
        <div></div>
    </div>
    <div></div>
    <div>
        <div></div>
        <div></div>
    </div>
</div>

To hide all immediate div children of #root, you can use the selector #root > div.

So, your jQuery might look like $('#root > div').hide()

Is that what you're trying to do?

Upvotes: 2

hjuster
hjuster

Reputation: 4070

I guess this is what you are trying to achieve.

$( "div:first" ).hide();

That will hide just the first div on the page. But anyway I would suggest to use the class or id...

So if you have more of them you should basically check wether their parent element is div, if it is, then don't hide them, otherwise hide. So...

            $('div').each(function(){
                _this = $(this);
                if(!_this.parent().is("div")){
                    _this.hide();
                }
            });

Upvotes: 1

Related Questions