Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all except some DOM elements in JQuery?

Tags:

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.

like image 251
Ivan Avatar asked Oct 04 '11 19:10

Ivan


1 Answers

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()

like image 176
zzzzBov Avatar answered Oct 13 '22 00:10

zzzzBov