Ivan
Ivan

Reputation: 15952

How to remove all except some DOM elements in JQuery?

I would like to remove all hidden elements in a piece of the DOM, but preserving all (included hidden items) under certain class.

Here you have a (non) working example:

<div id="init">
    <input type="hidden" name="x" value="y" />
    <ul>
        <li>Hello</li>
        <li>Bye</li>
        <li class="block">
            <ol>
                <li>First</li>
                <li>Second</li>
                <li>Third</li>
            </ol>
        </li>
        <li>Test</li>
    </ul>
</div>

CSS: li { "display:none" }

So, I'm looking for the selector that removes all hidden items except those that have a block class or are under a block class. In this case the expected result is:

<div id="init">
    <ul>
        <li class="block">
            <ol>
                <li>First</li>
                <li>Second</li>
                <li>Third</li>
            </ol>
        </li>
    </ul>
</div>

I've been playing with :not operator, but no success.

Upvotes: 11

Views: 11111

Answers (2)

Joe
Joe

Reputation: 82654

You can actually just use CSS:

li.block, li.block li { display: block }

Example


Or more comprehensive

li.block, li.block>* * { display: block }

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179284

You mean like this?

$(':hidden').not('.block, .block *').remove();

Alternatively:

$(':hidden:not(.block, .block *)').remove();

But $.fn.not() is a little more reliable than :not()

Upvotes: 13

Related Questions