0

我有很多 html 内容的输入。寻找一个 jquery 函数来有效地去除不需要的元素(只是元素,但需要保留内容),要保留的元素将是我指定的元素。还希望该功能易于配置以添加或删除我不想要的元素。例如: var tagsToRetain="p,i,u,br";

我在下面尝试过,但这需要指定我不想要的元素,这样做会很乏味。

$("span,h1,h2").each(function(){
$(this).replaceWith($(this).html());
});​
4

1 回答 1

0

如果我理解正确,您想指定循环不应处理哪些元素。.each()如果是这样,请使用:not()选择器.not()方法

$("body *:not(p,i,u,br)").each(function(){
   $(this).replaceWith($(this).html());
});​

// OR:
$("body *").not("p,i,u,br").each(function(){
   $(this).replaceWith($(this).html());
});​

// OR, encapsulated in a function with a clunky name:

function stripElementsNotSpecified(tagsToRetain) {
   $("body *").not(tagsToRetain).each(function(){
      $(this).replaceWith($(this).html());
   });
}

stripElementsNotSpecified("p,i,u,br");​

请注意,如果没有"body *"选择器部分,该:not(p,i,u.br)部分将选择文档的 html、head、脚本等元素。用"body *"它只选择身体的孩子。

于 2012-05-31T06:52:24.237 回答