开发者

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.


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜