删除嵌套标签的最简单方法

Easiest way to remove nested tags

我正在寻找使用 javascript.

从 DOM 元素中删除嵌套标签的最简单方法(编码和执行时间)

示例案例

<i><b>This <b><i>is <u>a</u> new</i></b> test</b></i>

求解:

<i><b>This is <u>a</u> new test</b></i>

该解决方案通常需要适用于所有可能的 html 标签,而不仅仅是上面的示例。 需要消除所有嵌套标签,同时保留 DOM.

中的内部 HTML

解决方案可能但不需要使用 jQuery。

有什么建议吗?

使用 find 方法,您可以在 <i> 标签内搜索 <b> 标签的所有子标签:

JS:

$('i b').find('b', 'i').contents().unwrap();

为了简单起见,您可以尝试这样做:

$("body *").each(function () {
    if ($(this).parents(this.nodeName.toLowerCase()).length) $(this).contents().unwrap();
});

-DEMO-

这是对 A.Woffs 关于代码执行的解决方案的一个小改进。 这样一来,每个 dom 节点就少了一个 jQuery 元素。 但是我不会为了这么小的改进而改变这个答案的公认答案。

$("body *").each(function () {
    var $this = $(this);
    if ($this.parents(this.nodeName.toLowerCase()).length) $this.contents().unwrap();
});