我有这个:
<div>content element</div>
<div class="accordionTrigger">
<div><h1>title</h1></div>
<p>text</p>
<p>text</p>
<p>text</p>
...
</div>
<div>content element</div>
<div>content element</div>
我需要将所有p-tag包装在div中,如下所示:
<div>content element</div>
<div class="accordionTrigger">
<div><h1>title</h1></div>
<div class="moreInfo">
<p>text</p>
<p>text</p>
<p>text</p>
...
</div>
</div>
<div>content element</div>
<div>content element</div>
可以用jQuery完成吗?
如果我有多个<div class="accordionTrigger"></div>
,请执行以下操作:
<div>content element</div>
<div class="accordionTrigger">
<div><h1>title</h1></div>
<p>text</p>
<p>text</p>
...
</div>
<div>content element</div>
<div class="accordionTrigger">
<div><h1>title</h1></div>
<p>text</p>
<p>text</p>
...
</div>
结果将是:
<div>content element</div>
<div class="accordionTrigger">
<div><h1>title</h1></div>
<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
...
</div>
<div>content element</div>
<div class="accordionTrigger">
<div><h1>title</h1></div>
</div>
我可以避免吗?
答案 0 :(得分:34)
检查.wrapAll()方法:
$('.accordionTrigger p').wrapAll('<div class="moreInfo"></div>');
wrapAll()方法将所有匹配的元素包装到另一个元素中(与.wrap()方法相比,后者单独包装匹配的元素)
<强> DEMO 强>
答案 1 :(得分:1)
检查一下它是否符合预期
<div>content element</div>
<div class="accordionTrigger">
<div><h1>title</h1></div>
<p>text</p>
<p>text</p>
<p>text</p>
<script type="text/javascript">
$("p").wrapAll("<div class='moreinfo'/>");
</script>
</div>
<div>content element</div>
<div>content element</div>