For a text annotation app I would like to programmatically color spans of text within a given div using previous user annotations, which are saved in the database as character offsets, e.g. - color character 0 to 6, color from 9 to 12, etc.
My approach has been to get the first #text node within the div (using an answer from 1), create a range there, and then insert the span there. But after the first span is inserted the first there is no longer a text element that contains all of the text in the div, and this fails:
function color_x_y(elementname, x, y){ // color from coordinate x to y, within div elementname
elem = get_text_node(elementname);
range = document.createRange();
range.setStart(elem, x);
range.setEnd(elem, y);
span = document.createElement("span");
span.style.border = "5px solid red";
range.expand();
span.appendChild(range.extractContents());
range.insertNode(span);
}
function get_text_node(node){
var oDiv = document.getElementById(node);
var firstText = "";
for (var i = 0; i < oDiv.childNodes.length; i++) {
var curNode = oDiv.childNodes[i];
if (curNode.nodeName === "#text") {
firstText = curNode;
break;
}
}
return firstText;
}
I am new to javascript and would appreciate any ideas on how to accomplish this.
Thanks!
EDIT
I should note that highlights may overlap with one another.