Reputation: 809
How can one create an element that wraps the content between two elements?
Here's a simplified example of the code I'm dealing with:
<p>
Some text some text <span class="foo">some more text</span> additional text.
</p>
<p>
I am bad at coming up with <span class="foo">fake text</span>, I should have looked it up lorem ipsum somewhere.
</p>
What I would like is that all the text between the end of the first span and the beginning of the second span to be wrapped in a div so that I can, for example, color the text differently.
Is such a thing possible? If not, are there any clever ways around this?
EDIT: I'm not entirely sure how I'd like the code to look at the end of the day. I only care about the result, which is that I'm able to apply specific styling to the text between the spans despite the fact that they have different parents. It would be really great if I could, for example, even set out the text and put a border around it, so that the end result looks something like:
Some text some text some more text
------------------------------
|additional text |
|I am bad at coming up with |
-----------------------------
fake text, I should have should have looked up lorem ipsum somewhere.
Upvotes: 1
Views: 461
Reputation: 253485
This is horrible, but it's the best I could come up with:
$('p').each(function(i){
var that = $(this),
foo = that.find('.foo');
if (i==0){
var tN = foo[0].nextSibling;
$('<span />',{class : 'fooSibling', text: tN.nodeValue}).insertAfter(foo);
}
else if (i==1){
var tN = foo[0].previousSibling;
console.log(tN,tN.nodeValue);
$('<span />',{class : 'fooSibling', text: tN.nodeValue}).insertBefore(foo);
}
this.removeChild(tN);
});
Slightly improved, and slightly less-horrible:
$('p').each(function(){
var that = $(this),
foo = that.find('.foo');
if (that.next().find('.foo').length){
$(foo[0].nextSibling).wrap('<span class="fooSibling"></span>')
}
else if (that.prev().find('.foo').length) {
$(foo[0].previousSibling).wrap('<span class="fooSibling"></span>')
}
});
Upvotes: 2