删除HTML标记,但保留innerHtml [英] Remove a HTML tag but keep the innerHtml

查看:63
本文介绍了删除HTML标记,但保留innerHtml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些简单的HTML,需要删除简单的格式.

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

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

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

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

在jQuery中这怎么可能?

How is this possible in jQuery?

推荐答案

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

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

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

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

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

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

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

这篇关于删除HTML标记,但保留innerHtml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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