开发者

How to remove all except some DOM elements in JQuery?

开发者 https://www.devze.com 2023-04-10 10:15 出处:网络
I would like to remove all hidden elements in a piece of the DOM, but preserving all (included hidden items) under certain class.

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.


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


You can actually just use CSS:

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

Example


Or more comprehensive

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

精彩评论

暂无评论...
验证码 换一张
取 消