Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove elements without a specified class

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]')");
like image 808
Vincent Peres Avatar asked Aug 24 '10 14:08

Vincent Peres


People also ask

How do you remove a specific class from all elements?

To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element.

How do I remove a nested element?

To remove elements from any sub-arrays of a nested array, use the “pop()” method.

How do you select all elements in a class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

How do you remove numbers from a range in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


2 Answers

Just do:

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

See the documentation:

jQuery(':not(selector)')

Selects all elements that do not match the given selector.

like image 178
Felix Kling Avatar answered Oct 03 '22 22:10

Felix Kling


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();
like image 38
meagar Avatar answered Oct 03 '22 21:10

meagar