Reputation: 4646
Suppose I have this HTML
<div class="parent">
<span class="foo">Some text</span>
<span class="foo">FROM HERE</span>
<span class="foo">some text</span>
<span class="foo">TO HERE</span>
<span class="foo">some text</span>
</div>
Now I'll already have the target elements as $(start)
and $(end)
. I want to make this html on a say a mouseup
<div class="parent">
<span class="foo">Some text</span>
<span class="highlight">
<span class="foo">FROM HERE</span>
<span class="foo">some text</span>
<span class="foo">TO HERE</span>
</span>
<span class="foo">some text</span>
</div>
and this I want to revert back.
This is related to this question where I already have the 'target elements'.
If it makes it easier, the structure will likely be always as above. A collection of spans
within a div
. I feel that jQuery nextUntil may be the best approach but I can't quite work it out.
Upvotes: 1
Views: 99
Reputation: 192132
You can wrap a collection of elements in jQuery, by using .wrapAll() and .unwrap():
Adding highlight:
var $wrapped = highlight($start, $end, '.foo'); // highlight and get the highlighted items collection
Removing highlight:
$wrapped.unwrap(); // use unwrap on the collection to remove highlight
Highlight func:
function highlight($start, $end) {
/** return the wrapped collection **/
return $start
.nextUntil($end) // get elements between $start and $end
.addBack() // add $start back
.add($end) // add $end
.wrapAll("<span class='highlight' />"); // wrap them with highlight
}
Upvotes: 1