Say I have 5 strong elements, and I want to wrap them in div elements, in groups of 2 using jQuery.
Example:
<!--original markup-->
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
Becomes
<!-- new markup -->
<div>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
</div>
<div>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
</div><div>
<strong>I AM STRONG</strong>
</div>
What would be the best way to do this? I have tried a few things but they were problematic. The strong elements can not have a fixed height. Also, these elements are for example only.
How would I write a jQuery loop to do this?
Thank you
Edit There is not a fixed number of elements.
I'd probably just loop two at a time, wrapping each pair as i go...
var elems = $("strong");
for (var i=0; i<elems.length; i+=2)
{
elems.slice(i,i+2) // split off a pair
.wrapAll("<div>"); // wrap it
}
You could use the :odd to select every other element, then .prev to get the even element.
$('strong:odd').each(function(){
var divElement = $('<div></div>').append($(this).prev(), $(this));
// Now add the divElement to a new container?
});
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.