I have the following code using rangy, which allows users to apply a class to selected text:
<div><span>This is some text that users can select</span></div>
When a user selects text and applies a class the code turns into:
<div><span>This is some <span class='someclass'>text</span> users can select</span</div>
I need a way to end the previous span tag first and then create a new one after:
<div><span>This is some </span><span class='someclass'>text</span><span> users can select</span</div>
The rangy library does not have a built in way to do this. I tried using:
$('.someclass').before("</span>")
and
$('.someclass').after("<span>")
but that did not work.
Any ideas?
Something like this will do
$('.someclass').parent().each(function(){
$(this).contents().each(function(){
if(this.nodeType == 3){
$(this).wrap('<span />')
}
});
$(this).contents().unwrap()
})
Demo: Fiddle