How to wrap various elements in a div tag with jQuery?
Asked Answered
C

4

6

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 summary it's just some headers with content below them, I just need everything below the header tags in a div like this:

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

I've tried using the .wrap function of jQuery but no luck since there can be multiple types elements below the header tags, I found this question: jQuery wrap sets of elements in div which is very similar but haven't been able to fit it into what I need, can anyone help me?

Thanks in advance!

Corneliuscornell answered 4/8, 2011 at 5:49 Comment(0)
S
7

You can try this:

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

$(function() {
    $('h5').each(function(i, e) {
        $(e).nextUntil('h5').wrapAll('<div>');
    });
});
Sextan answered 4/8, 2011 at 6:12 Comment(2)
Never knew about the nextUntil function, sweetEscapement
If you want to include the heading, add ".andSelf()", so line 3 becomes "$(e).nextUntil('h5').andSelf().wrapAll('<div>');" - Thanks, this was just what I needed.Marcosmarcotte
E
8

Do this:

$(document).ready(function () {
    $('h5').each(function () {
        $(this).nextUntil('h5').wrapAll('<div class="box"></div>');
    })
})
Eleemosynary answered 4/8, 2011 at 6:8 Comment(0)
S
7

You can try this:

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

$(function() {
    $('h5').each(function(i, e) {
        $(e).nextUntil('h5').wrapAll('<div>');
    });
});
Sextan answered 4/8, 2011 at 6:12 Comment(2)
Never knew about the nextUntil function, sweetEscapement
If you want to include the heading, add ".andSelf()", so line 3 becomes "$(e).nextUntil('h5').andSelf().wrapAll('<div>');" - Thanks, this was just what I needed.Marcosmarcotte
F
2

Try this

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()));
  }

});
Floyd answered 4/8, 2011 at 6:1 Comment(0)
E
1

I would just stick a div in the page after the h5, and manually insert the elements into it.

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

<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);
    }
}
Escapement answered 4/8, 2011 at 5:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.