I need to surround multiple words with spans, I know startIndex and endIndex for each word (I'm sure no word will be spanning in multiple tags and all the words are in the same element) I can't even select the first word, I get "IndexSizeError: Index or size is negative or greater than the allowed amount" and similar error with rangy ( / ) what am I doing wrong?
var range = document.createRange();
startNode = document.getElementById("texttocheck");
range.setStart(startNode, 0);
range.setEnd(startNode, 4);
var newNode = document.createElement("span");
range.surroundContents(newNode);
here is the fiddle: /
I need to surround multiple words with spans, I know startIndex and endIndex for each word (I'm sure no word will be spanning in multiple tags and all the words are in the same element) I can't even select the first word, I get "IndexSizeError: Index or size is negative or greater than the allowed amount" and similar error with rangy ( http://jsfiddle/pastrocchio/hgugQ/7/ ) what am I doing wrong?
var range = document.createRange();
startNode = document.getElementById("texttocheck");
range.setStart(startNode, 0);
range.setEnd(startNode, 4);
var newNode = document.createElement("span");
range.surroundContents(newNode);
here is the fiddle: http://jsfiddle/pastrocchio/hgugQ/3/
Share Improve this question edited Apr 22, 2013 at 10:53 chickpeas asked Apr 22, 2013 at 10:45 chickpeaschickpeas 4435 silver badges16 bronze badges 2- Are you only trying to select the first word or all of them? Do you have to use createRange() or can you use a different approach? – Derek Henderson Commented Apr 22, 2013 at 11:18
- some of them: the wrong ones, it will be a spellcheck – chickpeas Commented Apr 22, 2013 at 11:27
1 Answer
Reset to default 11I figured it out, I was missing startnode.firstChild
var range = document.createRange();
startNode = document.getElementById("texttocheck");
range.setStart(startNode.firstChild, 0);
range.setEnd(startNode.firstChild, 4);
var newNode = document.createElement("span");
range.surroundContents(newNode);