Reputation: 457
highlight is not a problem. my problem is, on how can i erase the highlight using window.getSelection() in javascript. and create a node new span closing and new span opening to erase the selected highlight areas. See the screenShots.
function removeHighlight(sel) {
if(sel.anchorNode.parentNode.className == 'hlt') {
var replacementText = sel.toString();
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(replacementText));
}
}
so far that is my function but createTextNode() can't read htmlEntities.
Upvotes: 4
Views: 441
Reputation: 10975
To achieve your expected result , follow below option
1.Get selected text from button-Toggle using id- toggle
2.Add close tag before selection element and span tag with class -'hlt' using 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>";
//var newHtml = oldHtml.replace(text, "</span>" + text + "<span class='hlt'>");
parent.html(output);
});
});
CSS:
.hlt{
background:yellow;
}
http://codepen.io/nagasai/pen/dXkZwP
Upvotes: 1