jQuery中将非子元素包装起来

3

目前我有一个以下格式的html文档:

<h1>a</h1>
<p>bla</p>
<p>more bla</p>

<h1>b</h1>
<p>different bla</p>

我正在寻找一种方法来将<h1>和其后面的<p>都包裹在一个div中,使其呈现为以下形式:
<div>
    <h1>a</h1>
    <p>bla</p>
    <p>more bla</p>
</div>

<div>
    <h1>b</h1>
    <p>different bla</p>
</div>

但是我使用wrap和wrapAll都没有成功实现这一点。

3个回答

6
var tagName = 'h1';
$(tagName).each(function ()
{
    var $this = $(this);
    $this.add($this.nextUntil(tagName)).wrapAll('<div></div>');
});

演示演示演示演示演示

(此链接为演示页面,无需翻译)

1
你可以创建一个 <div> 并将想要放入其中的元素移动到该 <div> 中,从而实现你想要的效果。
例如(可能还有更好的方法):
$("h1").before("<div></div>");
$("h1").each(function() {
    $(this)
        .nextUntil("h1").andSelf()
        .appendTo(
            $(this).prev("div")
        );
    });

谢谢 =) 先前的评论已删除。 - David Thomas

1

如果您能添加几个CSS类,可能会更容易。 请参见http://jsfiddle.net/avaXp/

<h1 class='one'>a</h1>
<p class='one'>bla</p>
<p class='one'>more bla</p>

<h1 class='two'>b</h1>
<p class='two'>different bla</p>



$('.one').wrapAll("<div></div>")
$('.two').wrapAll("<div></div>")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接