jQuery 删除 HTML 标记但保留 innerHtml

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4232961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:54:12  来源:igfitidea点击:

Remove a HTML tag but keep the innerHtml

jquery

提问by Ian Vink

I have some simple HTML which I need to strip simple formatting.

我有一些简单的 HTML,我需要去除简单的格式。

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

I need to remove the bold, but leave the sentence intact.

我需要删除粗体,但保持句子完整。

How is this possible in jQuery?

这在 jQuery 中怎么可能?

回答by user113716

$('b').contents().unwrap();

This selects all <b>elements, then uses .contents()to target the text content of the <b>, then .unwrap()to remove its parent <b>element.

这将选择所有<b>元素,然后用于.contents()定位 的文本内容<b>然后.unwrap()删除其父<b>元素。



For the greatest performance, always go native:

为了获得最佳性能,请始终使用本机:

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 ] );
}

This will be much faster than any jQuery solution provided here.

这将比此处提供的任何 jQuery 解决方案快得多。

回答by Nick Craver

You can also use .replaceWith(), like this:

你也可以使用.replaceWith(),像这样:

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

Or if you know it's just a string:

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

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

This can make a big difference if you're unwrapping a lot of elements since either approach above is significantly fasterthan the cost of .unwrap().

这可以使一个很大的区别,如果你因为以上两种方法是展开了很多元素的显著速度高于成本.unwrap()

回答by WebChemist

The simplest way to remove inner html elements and return only text would the JQuery .text() function.

删除内部 html 元素并仅返回文本的最简单方法是JQuery .text() 函数

Example:

例子:

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

jsFiddle 演示

回答by Toastrackenigma

How about this?

这个怎么样?

$("b").insertAdjacentHTML("afterend",$("b").innerHTML);
$("b").parentNode.removeChild($("b"));

The first line copies the HTML contents of the btag to the location directly after the btag, and then the second line removes the btag from the DOM, leaving only its copied contents.

第一行将b标签的 HTML 内容直接复制到标签之后的位置b,然后第二行将b标签从 DOM 中移除,只留下其复制的内容。

I normally wrap this into a function to make it easier to use:

我通常将它包装成一个函数以使其更易于使用:

function removeElementTags(element) {
   element.insertAdjacentHTML("afterend",element.innerHTML);
   element.parentNode.removeChild(element);
}

All of the code is actually pure Javascript, the only JQuery being used is that to select the element to target (the btag in the first example). The function is just pure JS :D

所有代码实际上都是纯 Javascript,唯一使用的 JQuery 是选择要定位的元素(b第一个示例中的标记)。该功能只是纯JS:D

Also look at:

还看看:

回答by redisko

// 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();
    }
  }
};

回答by izzulmakin

The simplest answer is mind blowing:

最简单的答案是令人兴奋的:

outerHTMLis supported down to Internet Explorer 4 !

Internet Explorer 4都支持外层 HTML

Here is to do it with javascript even without jQuery

即使没有 jQuery,这里也是用 javascript 来做的

function unwrap(selector) {
    var nodelist = document.querySelectorAll(selector);
    Array.prototype.forEach.call(nodelist, function(item,i){
        item.outerHTML = item.innerHTML; // or item.innerText if you want to remove all inner html tags 
    })
}

unwrap('b')

This should work in all major browser including old IE. in recent browser, we can even call forEach right on the nodelist.

这应该适用于所有主要浏览器,包括旧的 IE。在最近的浏览器中,我们甚至可以在节点列表上调用 forEach 。

function unwrap(selector) {
    document.querySelectorAll('b').forEach( (item,i) => {
        item.outerHTML = item.innerText;
    } )
}

回答by GijsjanB

Another native solution (in coffee):

另一个本地解决方案(在咖啡中):

el = document.getElementsByTagName 'b'

docFrag = document.createDocumentFragment()
docFrag.appendChild el.firstChild while el.childNodes.length

el.parentNode.replaceChild docFrag, el

I don't know if it's faster than user113716's solution, but it might be easier to understand for some.

我不知道它是否比 user113716 的解决方案快,但对某些人来说可能更容易理解。