如何在div中包含所有带有<p>的文本节点,该div也可能包含其他</p> <p>标签和标签,例如<strong>使用jQuery?</strong> </p>

时间:2015-03-28 10:49:50

标签: javascript jquery html

我有以下示例html:

<div>
Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.
<h1>Heading 1</h1>
<p>Some other text</p>
Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.
</div>

使用jQuery获得所需的结果:

<div>
<p>Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.</p>
<h1>Heading 1</h1>
<p>Some other text</p>
<p>Wrap this text with p which also includes <strong>this</strong> and also <a href="">this</a>.</p>
</div>

1 个答案:

答案 0 :(得分:2)

我认为您可以迭代div的内容并创建一组要包装的项目,如下所示

var $group = $();

$('div').contents().each(function () {
    if (this.nodeType == 3 || !$(this).is(':header, div, p')) {
        if (this.nodeType != 3 || this.nodeValue.trim()) {
            $group = $group.add(this);
        }
    } else {
        $group.wrapAll('<p />')
        $group = $()
    }
});
$group.wrapAll('<p />')

演示:Fiddle