我有以下示例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>
答案 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