我有一些简单的HTML,我需要剥离简单的格式。
A nice house was found in <b>Toronto</b>.
我需要去掉粗体,但保持句子不变。
这在jQuery中是如何实现的?
发布于 2010-11-20 21:45:39
您也可以使用.replaceWith()
,如下所示:
$("b").replaceWith(function() { return $(this).contents(); });
或者,如果你知道它只是一个字符串:
$("b").replaceWith(function() { return this.innerHTML; });
如果您要展开大量元素,这会产生很大的不同,因为上面的两种方法都比.unwrap()
的成本更高( significantly faster )。
发布于 2013-01-12 10:14:07
移除内部html元素并只返回文本的最简单方法是JQuery .text() function。
示例:
var text = $('<p>A nice house was found in <b>Toronto</b></p>');
alert( text.html() );
//Outputs A nice house was found in <b>Toronto</b>
alert( text.text() );
////Outputs A nice house was found in Toronto
发布于 2018-07-01 15:58:47
// For MSIE:
el.removeNode(false);
// Old js, w/o loops, using DocumentFragment:
function replaceWithContents (el) {
if (el.parentElement) {
if (el.childNodes.length) {
var range = document.createRange();
range.selectNodeContents(el);
el.parentNode.replaceChild(range.extractContents(), el);
} else {
el.parentNode.removeChild(el);
}
}
}
// Modern es:
const replaceWithContents = (el) => {
el.replaceWith(...el.childNodes);
};
// or just:
el.replaceWith(...el.childNodes);
// Today (2018) destructuring assignment works a little slower
// Modern es, using DocumentFragment.
// It may be faster than using ...rest
const replaceWithContents = (el) => {
if (el.parentElement) {
if (el.childNodes.length) {
const range = document.createRange();
range.selectNodeContents(el);
el.replaceWith(range.extractContents());
} else {
el.remove();
}
}
};
https://stackoverflow.com/questions/4232961
复制相似问题