刪除HTML標記但保留innerHtml我有一些簡單的HTML,我需要刪除簡單的格式。A nice house was found in <b>Toronto</b>.我需要刪除粗體,但保留句子完整。這怎么可能在jQuery中?
3 回答
手掌心
TA貢獻1942條經驗 獲得超3個贊
$('b').contents().unwrap();這將選擇所有<b>元素,然后用于.contents()定位文本內容<b>,然后.unwrap()刪除其父<b>元素。
為了獲得最佳性能,請始終使用原生:
var?b?=?document.getElementsByTagName('b');while(b.length)?{
????var?parent?=?b[?0?].parentNode;
????while(?b[?0?].firstChild?)?{
????????parent.insertBefore(??b[?0?].firstChild,?b[?0?]?);
????}
?????parent.removeChild(?b[?0?]?);}這將比這里提供的任何jQuery解決方案快得多。
斯蒂芬大帝
TA貢獻1827條經驗 獲得超8個贊
您也可以使用.replaceWith(),如下所示:
$("b").replaceWith(function()?{?return?$(this).contents();?});或者如果你知道它只是一個字符串:
$("b").replaceWith(function()?{?return?this.innerHTML;?});如果您打開很多元素,這可能會產生很大的不同,因為上述任何一種方法都明顯快于成本.unwrap()。
慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
刪除內部html元素并僅返回文本的最簡單方法是JQuery .text()函數。
例:
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?TorontojsFiddle演示
- 3 回答
- 0 關注
- 536 瀏覽
添加回答
舉報
0/150
提交
取消
