8

I've got a big HTML page. Some elements (can be p, h1, div etc.) are tagged with the class 'keep_me'. I need to remove all the elements present in the page WITHOUT this class? Any idea on how to do it with jQuery?

I tried with something like that, but it doesn't work (obviously ;) :

jQuery('#content *').remove(":not('[class=keep_me]')");

2 Answers 2

20

Just do:

jQuery('#content :not(.keep_me)').remove();

See the documentation:

jQuery(':not(selector)')

Selects all elements that do not match the given selector.

2
  • cheers, there was no example with a class so I deduced it was not working that way! Aug 24, 2010 at 14:37
  • @vincentp: You can use anything that is a valid selector. Aug 24, 2010 at 19:41
5

Use not():

The .not() method is typically faster and may end up providing you with more readable selections than pushing complex selectors or variables into a :not() selector filter.

$('#content *').not('.keep_me').remove();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.