如何从父母那里找到和解开元素?

时间:2014-03-26 03:43:33

标签: javascript jquery

如此简单,我正在尝试在我的页面上查找和解包元素。我的WYSIWYG编辑器出现了一些问题,我需要应用修复程序。

例如:

这就是我的HTML目前的样子

<h1>
    <p>Some text here</p>
    <p>Some text here</p>
    <p>Some text here</p>
    <img src="images/img.jpg" />
</h1>
<h1>
    <p>Some text here</p>
    <p>Some text here</p>
</h1>

我的HTML应如何显示

<p>Some text here</p>
<p>Some text here</p>
<p>Some text here</p>
<img src="images/img.jpg" />
<p>Some text here</p>
<p>Some text here</p>

如何完全删除h1代码?

这是我的尝试。一旦整个页面加载,我就会运行它。

if ($('h1').find('p').length) {
    $('p', this).unwrap();
}

PS。这总是随机发生,没有模式。有时可能会发生很多因素,有时只会发生在少数几个因素中。

2 个答案:

答案 0 :(得分:4)

您可以选择h1的子项并将其解包,如

$('h1 > *').unwrap();

var $h1 = $('h1');
$h1.contents().unwrap();
$h1.remove()

演示:Fiddle

注意:this引用的值不会在if条件内更改 - 从使用方式开始我假设您在this内部if block指的是h1元素


答案 1 :(得分:3)

您可以使用 .replaceWith()

$('h1').replaceWith(function() { return $(this).find('*'); });

<强> Fiddle Demo

相关问题