$('xxxx').html() 把 DOM 节点转成字符串后,如何快速从字符串中剔除某个节点?

2014 年 6 月 19 日
 paloalto
现在我的做法是先 .clone(),然后 .remove()。

var $content = $('#content').clone();
$content.find('.class-1, .class-2, .class-3').remove();
var content = $content.html();

最终的 content 就是 剔除后某节点的字符串了。

但是这么做有点笨,有没有更好的处理办法?
6098 次点击
所在节点    前端开发
7 条回复
lijsh
2014 年 6 月 19 日
写个函数封装下就不笨了,哈哈
yyfearth
2014 年 6 月 19 日
哪里笨了 不就这样么

如果你只有字符串 那么也就是 (类似)
var $content = $(content_html_string);
content.find('xxx').remove();
var content = content.html()

如果你想用regex处理string那就更麻烦而且不靠普了
yyfearth
2014 年 6 月 19 日
抱歉 第二行应该是 $content.find('.class-1, .class-2, .class-3').remove();
icanfork
2014 年 6 月 19 日
$(content_html_string).find('class').remove();
switch
2014 年 6 月 19 日
可以这样:
$("#content").clone().find(".class-1, .class-2, .class-3").remove().end();
switch
2014 年 6 月 19 日
$("#content").clone().find(".class-1, .class-2, .class-3").remove().end().html()
justfindu
2014 年 6 月 19 日
你这个方法so 机智 ...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/118303

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX