How to wrap various elements in a div tag using jQuery?

I have an html structure that looks like this:

<h5>Title</h5> <p> Content </p> <ul> <li>Item</li> <li>Item</li> </ul> <p> Content </p> <h5>Title</h5> <p> Content </p> <ul> <li>Item</li> <li>Item</li> </ul> <p> Content </p> 

In general, these are just some of the headers with the content below them, I just need everything under the headers in the div like:

 <h5>Title</h5> <div> <p> Content </p> <ul> <li>Item</li> <li>Item</li> </ul> <p> Content </p> </div> 

I tried using the .wrap function for jQuery, but no luck, as there may be several type elements under the header tags, I found this question: jQuery wraps the element sets in a div that is very similar, but could not fit it into what I need someone can help me?

Thanks in advance!

+6
source share
4 answers

You can try the following:

http://jsfiddle.net/GGjXN/1/

 $(function() { $('h5').each(function(i, e) { $(e).nextUntil('h5').wrapAll('<div>'); }); }); 
+5
source

Do it:

 $(document).ready(function () { $('h5').each(function () { $(this).nextUntil('h5').wrapAll('<div class="box"></div>'); }) }) 
+7
source

try it

 var $div; $("h5").each(function(){ $div = $("<div />"); if($(this).nextAll("h5").length){ $(this).after($div.append($(this).nextUntil("h5"))); } else{ $(this).after($div.append($(this).siblings())); } }); 
+2
source

I would just hit the div on the page after h5 and manually insert elements into it.

Assuming everything is something inside, like the body (untested!) Tag:

 <body> <h5>Title</h5> <p> Content </p> <ul> <li>Item</li> <li>Item</li> </ul> <p> Content </p> </body> var children = $(document.body).children(), $child $div; for(var x = 0, child; child = children[x++];) { $child = $(child); if($child.is('h5')) { $div = $('<div></div>').after($child); } else { $child.appendTo($div); } } 
+1
source

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


All Articles