给出以下HTML:
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<h1>Interruption</h1>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
我需要的是以下内容:
<div class="wrapper">
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
</div>
<h1>Interruption</h1>
<div class="wrapper">
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
</div>
使用jQuery有一个简单的方法吗?我找到了.wrapAll(),但这会给我:
<div class="wrapper">
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
</div>
<h1>Interruption</h1>
答案 0 :(得分:3)
使用 .nextUntil
来识别h1
出现的位置并使用 .wrapAll
。
$('div[class^="ms-rteElement"]').each(function(){
$(this).wrapAll('<div class="wrapper"></div>').nextUntil('h1');
})
.wrapper{
background:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<h1>Interruption</h1>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
答案 1 :(得分:0)
也许这很有用
$( "h1" ).prevAll('.ms-rteElement-accordion-headline, .ms-rteElement-accordion-content').wrapAll('<div class="wrapper" />');
$( "h1" ).nextAll('.ms-rteElement-accordion-headline, .ms-rteElement-accordion-content').wrapAll('<div class="wrapper" />');
但是你应该将它包含在div
中答案 2 :(得分:-1)