[英]How do I wrap all text nodes with <p> in a div that also may contain other <p> tags and tags such as <strong> using jQuery?
我有以下示例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>
我认为您可以遍历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 />')
演示: 小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.