Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't surroundContents with range set.Start set.setEnd

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.net/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.net/pastrocchio/hgugQ/3/

like image 420
chickpeas Avatar asked Dec 26 '22 05:12

chickpeas


1 Answers

I 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);
like image 109
chickpeas Avatar answered Jan 10 '23 09:01

chickpeas