59057

Question:
I have a HTML structure like so:
<section>
<item>
<ele class="blue" />
<ele class="green" />
<ele class="red" />
</item>
<item>
<ele class="blue" />
<ele class="green" />
<ele class="red" />
</item>
<item>
<ele class="blue" />
<ele class="green" />
<ele class="red" />
</item>
</section>
I need to wrap the second two elements inside each <item>
in a new div, so that it looks like the following:
<item>
<ele class="blue" />
<div class="extra-wrapper">
<ele class="green" />
<ele class="red" />
</div>
</item>
Is it possible to use any of the jQuery wrap
functions to achieve this? Or is there another way, without having to filter through each item, find the matching elements within, build a new string of HTML and put them back in?
To do this you can loop over each .blue
element, get all the following siblings and call wrapAll()
on them, like this:
$('.blue').each(function() {
$(this).nextAll().wrapAll('<div class="extra-wrapper"></div>');
});
<pre class="snippet-code-css lang-css prettyprint-override">.extra-wrapper {
border: 1px solid #C00;
}
<pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div>
<div class="blue">blue</div>
<div class="green">green</div>
<div class="red">red</div>
</div>
<div>
<div class="blue">blue</div>
<div class="green">green</div>
<div class="red">red</div>
</div>
<div>
<div class="blue">blue</div>
<div class="green">green</div>
<div class="red">red</div>
</div>
</section>
Note that I changed the <ele />
and <item />
element to divs as they were non-standard.