Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping non-child elements in jquery

Tags:

html

jquery

dom

I currently have a html document in the following format:

<h1>a</h1>
<p>bla</p>
<p>more bla</p>

<h1>b</h1>
<p>different bla</p>

I am looking for a way to wrap both the <h1> and it's following <p> inside a div, so it would look like:

<div>
    <h1>a</h1>
    <p>bla</p>
    <p>more bla</p>
</div>

<div>
    <h1>b</h1>
    <p>different bla</p>
</div>

But I have been unsuccessful using wrap and wrapAll to achieve this.

like image 591
ikkebr Avatar asked Dec 09 '25 23:12

ikkebr


2 Answers

var tagName = 'h1';
$(tagName).each(function ()
{
    var $this = $(this);
    $this.add($this.nextUntil(tagName)).wrapAll('<div></div>');
});

Demo demo demo demo demo

like image 173
Matt Ball Avatar answered Dec 11 '25 12:12

Matt Ball


If you can add a few more css classes it might be easier. See http://jsfiddle.net/avaXp/

<h1 class='one'>a</h1>
<p class='one'>bla</p>
<p class='one'>more bla</p>

<h1 class='two'>b</h1>
<p class='two'>different bla</p>



$('.one').wrapAll("<div></div>")
$('.two').wrapAll("<div></div>")
like image 23
chrisp_68 Avatar answered Dec 11 '25 12:12

chrisp_68