I'm trying to wrap multiple same class divs into a div and to skip divs not with the same class. .wrap doesn't combine them, and .wrapAll throws the non-classed divs underneath. I've been tinkering around with attempts to create an alternate solution but with no avail.
Original:
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div>Skip in wrap</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
continued...
Wanted Result:
<div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
</div>
<div>Skip in wrap</div>
<div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
</div>
Well you can have 2 div's with the same name provided one is an “div id” and the other is a “div class”. But you can't have the same name for two “divs” or “classes”. jatinsays: you can't have the same name for two “divs” or “classes”.
wrapAll( wrappingElement )Returns: jQuery. Description: Wrap an HTML structure around all elements in the set of matched elements.
You can fill a whole div or other parent element container in HTML with a link tag inside the div using some positioning attributes in CSS. The link tag is absolutely positioned to its parent which is relatively positioned, and will now fill the whole parent tag.
jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector). wrap(wrappingElement,function(index))
You can loop pretty quickly through your <div>
elements using a for
loop. In the below code, just change the initial selector here to grab all those siblings divs, e.g. #content > div.entry
or wherever they are:
var divs = $("div.entry");
for(var i=0; i<divs.length;) {
i += divs.eq(i).nextUntil(':not(.entry)').andSelf().wrapAll('<div />').length;
}
You can give it a try here. We're just looping through, the .entry
<div>
elements using .nextUntil()
to get all the .entry
elements until there is a non-.entry
one using the :not()
selector. Then we're taking those next elements, plus the one we started with (.andSelf()
) and doing a .wrapAll()
on that group. After they're wrapped, we're skipping ahead either that many elements in the loop.
I just whipped up a simple custom solution.
var i, wrap, wrap_number = 0;
$('div').each(function(){ //group entries into blocks "entry_wrap_#"
var div = $(this);
if (div.is('.entry')) {
wrap = 'entry_wrap_' + wrap_number;
div.addClass(wrap);
} else {
wrap_number++;
}
});
for (i = 0; i <= wrap_number; i++) { //wrap all blocks and remove class
wrap = 'entry_wrap_' + i;
$('.' + wrap).wrapAll('<div class="wrap"/>').removeClass(wrap);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With