javascriptjquerywrapall

wrapping divs with jQuery


I need to wrap some divs into another div with jQuery, the original output looks like this:

<div>Some content</div>
<div>Some content</div>

<h3>Local</h3>
<div>Some content</div>
<div>Some content</div>
<div>Some content</div>

<h3>Non-Local</h3>
<div>Some content</div>
<div>Some content</div>
<div>Some content</div>

And I would need to wrap them so they look like this:

<div>
    <div>Some content</div>
    <div>Some content</div>
</div>

<div>
    <h3>Local</h3>
    <div>Some content</div>
    <div>Some content</div>
    <div>Some content</div>
</div>

<div>
    <h3>Local</h3>
    <div>Some content</div>
    <div>Some content</div>
    <div>Some content</div>
</div>

The divs can't be identified by any id or class, so I would need to find a way to wrap all divs that follow an h3.


Solution

  • You could

    The reason to save the groups in a groups array first is, to not change the HTML structure until having looped over each collection. Otherwise, the subsequent calls will find the added elements as well.

    Here's the example code.