I need to wrap everything, including free text, that is between two <hr> elements.
Given this source:
<hr class=begin>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<a href=mauris.html>Mauris</a> id diam turpis, et faucibus nunc.
<div><img src=foo.png /></div>
<hr class=end>
I need to wrap everything between the hr.begin and hr.end tags, like so:
<hr class=begin>
<div class=content>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<a href=mauris.html>Mauris</a> id diam turpis, et faucibus nunc.
<div><img src=foo.png /></div>
</div>
<hr class=end>
I cannot use a method like .nextUntil('hr.end') because this will not select the untagged text.
Updated
I like this version better than my previous: http://jsfiddle.net/LbmCg/3/
(Partly inspired from the answer J-P gave.)
Original answer
Try this: http://jsfiddle.net/LbmCg/
If there’s more than one set to wrap, there will some adjustment needed.
jQuery’s
.contents()returns all nodes including text nodes. So here we traverse to the.parent()of thehr.begin, get all of its nodes using.contents()then filter through them, tracking when we’ve found the beginning and the end, and only returning the elements between them.Then we use
.wrapAll()to wrap them with thediv.content.EDIT: If there are multiple sets to wrap, try this: http://jsfiddle.net/LbmCg/1/
EDIT: Cleaned things up a little in both examples.