首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >移除HTML标签,但保留innerHtml

移除HTML标签,但保留innerHtml
EN

Stack Overflow用户
提问于 2010-11-20 21:31:08
回答 4查看 115.4K关注 0票数 160

我有一些简单的HTML,我需要剥离简单的格式。

A nice house was found in <b>Toronto</b>.

我需要去掉粗体,但保持句子不变。

这在jQuery中是如何实现的?

EN

回答 4

Stack Overflow用户

发布于 2010-11-20 21:45:39

您也可以使用.replaceWith(),如下所示:

$("b").replaceWith(function() { return $(this).contents(); });

或者,如果你知道它只是一个字符串:

$("b").replaceWith(function() { return this.innerHTML; });

如果您要展开大量元素,这会产生很大的不同,因为上面的两种方法都比.unwrap()的成本更高( significantly faster )。

票数 54
EN

Stack Overflow用户

发布于 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

jsFiddle Demo

票数 14
EN

Stack Overflow用户

发布于 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();
    }
  }
};
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4232961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档