views:

28

answers:

4

Hi,

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]')");
+4  A: 

Just do:

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

See the documentation:

jQuery(':not(selector)')

Selects all elements that do not match the given selector.

Felix Kling
cheers, there was no example with a class so I deduced it was not working that way!
vincentp
@vincentp: You can use anything that is a valid selector.
Felix Kling
A: 

have you tried sth like this

if($('#some_id').hasClass('myclass')) {
  ... do something ...
}
else {
  ... do something else ...
}
Flakron Bytyqi
Not really relevant to the question.
meagar
How would you do that with more than one element?
Felix Kling
A: 
$('#content').find('*').not('.keep_me').remove();

It's probably better (faster), to reverse the whole thing:

var $content = $('#content'),
var $keep    = $content.find('.keep_me');

$content.replaceWith($keep);
jAndy
+1  A: 

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