To achieve the expected result, follow the option below
1.Select the selected text using the-Toggle button using id-toggle
2. Add a close tag in front of the selection element and a span tag with the -'hlt 'class using a substring
HTML:
<p>
Lorem ipsum dolor sit amet, cursus laoreet tincidunt vel, at purus sagittis ultrices <span class="hlt">varius elit accumsan, sed nulla aenean amet, nulla ac et, imperdiet </span>fermentum nulla ipsum risus leo.
</p>
<button id="toggle">Toggle</button>
JS:
$(document).ready(function() {
$("#toggle").click(function() {
$('span.hlt').removeClass('hlt');
var selection = window.getSelection();
var text = selection.toString();
var parent = $(selection.focusNode.parentElement);
var oldHtml = parent.html();
var position = oldHtml.indexOf(text);
var end =(position*1)+selection.length
console.log(text.length);
var output = "<span class='hlt'>" +oldHtml.substr(0, position) + "</span>"+text+"<span class='hlt'>" + oldHtml.substr(position+text.length)+ "</span>";
parent.html(output);
});
});
CSS
.hlt{
background:yellow;
}
http://codepen.io/nagasai/pen/dXkZwP