admin管理员组文章数量:1405373
I want to select all elements between two given elements. I have html like this...
<h2>This is firsty</h2>
<p>Some para</p>
<ul>
<li>list items</li>
<li>list items</li>
<li>list items</li>
<li>list items</li>
<li>list items</li>
</ul>
<h2>Secondy</h2>
<p>More text</p>
I want to select everything from the first h2
to the second h2
, so I can wrap it in a div
, ending up with all sections in their own wrapper.
I want to select all elements between two given elements. I have html like this...
<h2>This is firsty</h2>
<p>Some para</p>
<ul>
<li>list items</li>
<li>list items</li>
<li>list items</li>
<li>list items</li>
<li>list items</li>
</ul>
<h2>Secondy</h2>
<p>More text</p>
I want to select everything from the first h2
to the second h2
, so I can wrap it in a div
, ending up with all sections in their own wrapper.
1 Answer
Reset to default 7I'd suggest:
var elems = $('h2:first').nextUntil('h2');
Or, to perform the actual wrapping:
$('h2:first').nextUntil('h2').wrapAll('<div />');
More generically:
$('h2').each(
function(i,e) {
$(this)
.nextUntil(this.tagName)
.wrapAll('<div />');
});
JS Fiddle demo.
In order to include the starting element simply use andSelf()
as part of the selector chain:
$('h2:first').nextUntil('h2').andSelf().wrapAll('<div />');
JS Fiddle demo.
Update for jQuery v3+
andSelf()
was removed in v3 and should be replaced with addBack()
:
$('h2:first').nextUntil('h2').addBack().wrapAll('<div />');
References:
andSelf()
.nextUntil()
.wrapAll()
.
本文标签: javascripthow can I select all elements between two elementsStack Overflow
版权声明:本文标题:javascript - how can I select all elements between two elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744321101a2600500.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论