繁体   English   中英

我如何包装所有文本节点 <p> 在div中可能还包含其他 <p> 标签和<strong>使用jQuery之类的</strong>标签<strong>?</strong>

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM