如何删除没有指定类的元素

Vin*_*res 8 jquery jquery-selectors

我有一个很棒的HTML页面.一些元素(可以是p,h1,div等)用类'keep_me'标记.我需要删除页面中没有这个类的所有元素吗?关于如何使用jQuery做任何想法?

我试过类似的东西,但它不起作用(显然;):

jQuery('#content *').remove(":not('[class=keep_me]')");
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 19

做就是了:

jQuery('#content :not(.keep_me)').remove();
Run Code Online (Sandbox Code Playgroud)

查看文档:

jQuery的( ':否(选择)')

选择与给定选择器不匹配的所有元素.


mea*_*gar 5

使用not():

.not()方法通常更快,并且可能最终为您提供比将复杂选择器或变量推送到:not()选择器过滤器更可读的选择.

$('#content *').not('.keep_me').remove();
Run Code Online (Sandbox Code Playgroud)