How to wrap all elements inside a div after a specific element? (Jquery)

I have an article tag that has elements inside.

Problem: How can I wrap all elements inside a div after a specific 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 conclusion should 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>

+5
source share
1 answer

As suggested by @squint, jQuery has a wrapAll method that can do this in combination with next-siblings-selector ~

 $("article > figure ~ *").wrapAll("<div class='description-wrap'></div>") 

however, this does not give the desired result if you have several articles. Instead, we need to use .each() like this:

 $("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> 
+4
source

Source: https://habr.com/ru/post/1203730/


All Articles