I have an article tag that has elements inside it.
Problem: How can I wrap all elements inside a div after a certain element?
This is the current code:
<article>
<figure class="thumbnail">
<img src="src_to_img" />
</figure>
<h2>Name: Test Name</h2>
<div class="description"></div>
<div class="content"></div>
<div class="content"></div>
<div class="more"></div>
<article>
The output must be:
<article>
<figure class="thumbnail">
<img src="src_to_img" />
</figure>
<div class="description-wrap">
<h2>Name: Test Name</h2>
<div class="description"></div>
<div class="content"></div>
<div class="content"></div>
<div class="more"></div>
</div>
<article>
As you can see.. the final output has all the elements wrapped inside class="description-wrap"
after <figure></figure>
As @squint suggested, jQuery has a wrapAll method that can do that if combined with the next-siblings-selector ~
$("article > figure ~ *").wrapAll("<div class='description-wrap'></div>")
however, this doesn't give you the desired output when you have multiple articles. Instead we need to use .each()
like so:
$("article > figure").each(function(){
$(this).siblings().wrapAll("<div class='description-wrap'></div>")
});
.description-wrap {border:1px dotted red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<article>
<figure class="thumbnail">
<img src="src_to_img" />
</figure>
<h2>Name: Test Name</h2>
<div class="description"></div>
<div class="content"></div>
<div class="content"></div>
<div class="more"></div>
</article>
<article>
<figure class="thumbnail">
<img src="src_to_img" />
</figure>
<h2>Name: Test Name</h2>
<div class="description"></div>
<div class="content"></div>
<div class="content"></div>
<div class="more"></div>
</article>
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