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]')");
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.
To remove elements from any sub-arrays of a nested array, use the “pop()” method.
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 (.)
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.
Just do:
jQuery('#content :not(.keep_me)').remove();
See the documentation:
jQuery(':not(selector)')
Selects all elements that do not match the given selector.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With