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.

Share Improve this question asked Oct 9, 2012 at 7:25 Billy MoonBilly Moon 58.7k27 gold badges148 silver badges244 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

I'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