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.
Theorically jQuery functions "next()" or "nextAll()" or "nextUntill()" allow you to find the following sibling(s) of a selected element. So you could try something with thoose function depending of the structure of your html.
More help in jQuery doc here in the jQuery API doc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.