How can I select all elements between two elements

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 , as a result, all sections in their own shell.

+4
source share
1 answer

I would suggest:

 var elems = $('h2:first').nextUntil('h2'); 

Or, to complete the actual packaging:

 $('h2:first').nextUntil('h2').wrapAll('<div />'); 

In a more general form:

 $('h2').each( function(i,e) { $(this) .nextUntil(this.tagName) .wrapAll('<div />'); });​ 

JS Fiddle demo .

To include the source element, simply use andSelf() as part of the selector chain:

 $('h2:first').nextUntil('h2').andSelf().wrapAll('<div />'); 

JS Fiddle demo .

Literature:

+5
source

Source: https://habr.com/ru/post/1438582/


All Articles