最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't surroundContents with range set.Start set.setEnd - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 11

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);
发布评论

评论列表(0)

  1. 暂无评论