How to remove everything except some DOM elements in jQuery?

I would like to remove all hidden elements in a DOM chunk, but save everything (including hidden elements) in a specific 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 am looking for a selector that removes all hidden elements except those that have a block class or are under a block class. In this case, the expected result:

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

I played with: not an operator, but without success.

+7
source share
2 answers

Do you mean this?

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

As an alternative:

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

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

+8
source

In fact, you can just use CSS:

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

Example


Or more comprehensive

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

All Articles