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.
You could
nextUntil()
- function of jQuery to look for div elements following the h3, 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.