Search code examples
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

    • loop over the h3 elements
    • use the nextUntil() - function of jQuery to look for div elements following the h3,
    • add them to the collection
    • push each of them into the group array
    • and then loop over the groups, and wrap each of them inside a div

      var groups = [];

      $('h3').each(function(index, value) {

      $head = $(value);

      var $group = $head.add($head.nextUntil('h3', 'div')); groups.push($group);

      });

      for (group in groups) {

      $(groups[group]).wrapAll('');

      }

    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.