Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

The fastest way is to change the code for handling the span class insertion into:

insert before selection

</span><span class='someclass'>

and after selection

</span><span>

Play with range and surroundContents:

var spanparent = $('div > span').get(0);
var range = document.createRange();

// create <span>This is some </span>
var startSpan = document.createElement("span");
range.setStart(spanparent,0);
range.setEnd(spanparent,1);
range.surroundContents(startSpan);

// create <span> users can select</span>
var endSpan = document.createElement("span");
range.setStart(spanparent,2);
range.setEnd(spanparent,3);
range.surroundContents(endSpan);

//result:
//<div>
//  <span>
//      <span>This is some </span>
//      <span class="someclass">text</span>
//      <span> users can select</span>
//  </span>
//</div>

// remove the outer span
var contents = $(spanparent).html();
$(spanparent).replaceWith(contents);

hope this helps

Give the div an id of lets say myDiv.

$(function(){
   var selectedText = ""; // Store the selected text in this variable
   var indexOfText = $("#myDiv").text().indexOf(selectedText);
   var originalString = $("#myDiv").text();
   var part1 = originalString.substring(0, indexOfText);
   var part2 = originalString.substring(indexOfText + selectedText.length, originalString.length - 1);
   var newString = "<span>" + part1 + "</span><span>" + selectedText + "</span><span>" + part2 + "</span>";
   $("#myDiv").empty();
   $("#myDiv").html(newString);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top