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.
If you HR and other tags are inside a div e.g.
You can use jQuery.contents() e.g.
outputs:
So you can easily club them in groups as you need.
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.
Had a similar problem, but I was using a CMS based on FCKEditor that didn't work so hot because of insertion of newline TextNodes from using the nextSibling property. I generally don't like to mix jQuery stuff with native JavaScript if I can help it either. I came up with this snippet that updates Patrick DW's solution that would probably be a bit more friendly for jQuery usage. Also doesn't require classes to determine next block.
theElement.contents()
will recognize text nodes. SincejQuery.nextUntil()
is actually a wrapper aroundjQuery.dir
, which doeswhere text nodes that get filtered out have a
nodeType
of 3, a customjQuery.dir
might help here.—
I tried this solution with Patrick’s test data and it works:
A extended version of user191688's code. This on is not only looking for the "until" in siblings but also up and down the tree.
This can handle multiple sets of the
begin - contents - end
sequence. It will look for allhr.end
elements preceded byhr.begin
elements and will, for eachhr.end
, find the preceding nodes between it andhr.begin
, and then it'll wrap them all in a<div class=content>
.