Wrapping non-child elements in jquery
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开发者_StackOverflow社区</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.
var tagName = 'h1';
$(tagName).each(function ()
{
var $this = $(this);
$this.add($this.nextUntil(tagName)).wrapAll('<div></div>');
});
Demo demo demo demo demo
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>")
What you could do would be to create a <div>
where you want it in the DOM, and then move the elements you want to be inside it into it.
For example (probably could be better):
$("h1").before("<div></div>");
$("h1").each(function() {
$(this)
.nextUntil("h1").andSelf()
.appendTo(
$(this).prev("div")
);
});
精彩评论