chickpeas
chickpeas

Reputation: 443

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/

Upvotes: 5

Views: 2252

Answers (1)

chickpeas
chickpeas

Reputation: 443

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);

Upvotes: 11

Related Questions