jQuery:从字符串中剥离所有特定的HTML标记 [英] Jquery: Strip all specific HTML tags from string

查看:118
本文介绍了jQuery:从字符串中剥离所有特定的HTML标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一串文本和html标签的变量,例如:

I have a variable that contains a string of text and html tags, such as:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";

我想删除某种类型的所有标签.例如,假设所有pspan标签.

I would like to remove all tags of a certain type. Let's say all p and span tags for example.

这是我能想到的最好的方法

This is the best I can come up with:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";
var $temp = $(temp);
$("p", $temp).replaceWith("foo");
alert($temp.html());  //returns "Some text"

我能找到的最接近的答案是尼克·克拉弗(Nick Craver)的答案:条带跨度带有jquery的字符串中的代码.

The closest response I could find is this answer by Nick Craver: strip span tags from string with jquery.

推荐答案

演示: http://jsfiddle.net/VwTHF/1/

$('span, p').contents().unwrap();

.contents() 将获取每个此类标记中的元素和文本,并

.contents() will get the elements and text within each such tag, and .unwrap will remove the element wrapping each content section.

根据您当前的方法,它看起来像这样:

Based on your current approach it would look something like this:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";
var $temp = $(temp);
$temp.find('span, p').contents().unwrap().end().end();

如果要继续定位原始对象,则必须使用.end()清除过滤器.

If you want to continue targeting the original object, you have to use .end() to clear the filter.

这篇关于jQuery:从字符串中剥离所有特定的HTML标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆