I'm currently struggling to figure out how to manipulate text elements within a span
. When a user selects a portion of text in a div, I successfully append a span
element. However, if the user selects the same text again, I want to remove the existing span
and wrap the selection in a new span
, ensuring that there are no children for any span
element (aside from other span elements).
Does anyone know how to clear the span
during text selection?
In my code, I am applying borders to the spans to highlight them.
JavaScript Code:
function manipulativeSpan() {
var newSpan = document.createElement("span");
var selectedRange = getSelection().getRangeAt(0);
console.log(selectedRange);
try {
selectedRange.surroundContents(newSpan);
$(newSpan).addClass('highlight');
} catch (exception) {
console.log("The Range has partially selected a non-Text node.")
}
}
$("#addText").on('click', function(event) {
event.preventDefault();
$(manipulativeSpan());
});
$("button").click(function(){
$(manipulativeSpan());
});
$("div.content").mouseup(function(event) {
var range = window.getSelection().getRangeAt(0);
if (!range.collapsed) {
var bounds = range.getBoundingClientRect();
var x = bounds.left + ((bounds.right - bounds.left - $(".savetooltipAll").outerWidth()) / 2);
var y = bounds.top - $(".savetooltipAll").outerHeight() + $(window).scrollTop();
$(".savetooltipAll").css("top", (y+(bounds.top*3)) + 'px');
$(".savetooltipAll").css("left",x + 'px');
$(".savetooltipAll").show();
} else {
$(".savetooltipAll").hide();
}
});
$("div.content").mousedown(function(event) {
var range = window.getSelection();
console.log(range.type);
});