Duplicate:
How can I add a parent element to a group of paragraph?
I have the following HTML blocks repeated in the document
<!-- first block -->
<div class="first">
My first div
</div>
<div class="second">
My second div
</div>
<!-- second block -->
<div class="first">
My first div
</div>
<div class="second">
My second div
</div>
...
How can I wrap the Divs with jQuery to get the resulting HTML like this...
<!-- first block -->
<div class="container">
<div class="first">
My first div
</div>
<div class="second">
My second div
</div>
</div>
<!-- second block -->
<div class="container">
<div class="first">
My first div
</div>
<div class="second">
My second div
</div>
</div>
...
You're in luck, that's exactly what wrapAll
is for:
$(".first, .second").wrapAll('<div class="container"></div>');
Your edit markedly changes the question. If you need to do the above only within some containing block, you can loop through the containing blocks and apply wrapAll
only to their contents. You'll need a way to identify the way you want to group your divs, which you haven't specified in the question.
If the divs have some kind of container around them, you can do this:
$(".block").each(function() {
$(this).find(".first, .second").wrapAll('<div class="container"></div>');
});
In that example, I've assumed the divs are within a container with the class "block"
.
If there's no structural way to identify them, you'll have to do it some other way. For instance, here we do it by assuming any time we see a first
, we should stop grouping:
var current = $();
$(".first, .second").each(function() {
var $this = $(this);
if ($this.hasClass('first')) {
doTheWrap(current);
current = $();
}
current = current.add(this);
});
doTheWrap(current);
function doTheWrap(d) {
d.wrapAll('<div class="container"></div>');
}
That works because $()
gives you the elements in document order, so if we loop through them in order, saving them up, and then wrap up the previous ones whenever we see a new first
(and of course, clean up at the end), you get the desired result.
Or here's another way to do that same thing, which doesn't use wrapAll
. It relies on the first matched element being a first
(so no second
s before first
s!):
var current;
$(".first, .second").each(function() {
var $this = $(this);
if ($this.hasClass('first')) {
current = $('<div class="container"></div>').insertBefore(this);
}
current.append(this);
});