Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught DOMException: Failed to execute 'setStart' on 'Range': The offset is larger than the node's length

The following code is often throwing an error that reads

Uncaught DOMException: Failed to execute 'setStart' on 'Range': The offset some integer is larger than the node's length (some smaller integer).

var range = document.createRange();
range.setStart(pos.node, pos.position + someNumber);

pos is set like so:

getTextNodeAtPositionAndReturnEndOfContextIfNeeded = function(root, index){
  var lastNode = null;
  var nodeCount = 0;
  var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, function next(elem) {
    nodeCount++;
    if(index > elem.textContent.length){
      index -= elem.textContent.length;
      lastNode = elem;
      return NodeFilter.FILTER_REJECT;
    }
    return NodeFilter.FILTER_ACCEPT;
  }, true); //true was added as a parameter to satisfy ie, but I haven't determined if it still works in other browsers, seems fine in Chrome so far.
  var c = treeWalker.nextNode();
  return {
    node: c ? c : root,
    position: c ? 0 : nodeCount
  };
}

var pos = getTextNodeAtPositionAndReturnEndOfContextIfNeeded(context, len);

What I'm looking for is how to determine the node's length in advance of calling range.setStart, but I'm not sure where to access that.

I'm guessing that I can add something like this:

return {
  node: c ? c : root,
  position: c ? 0 : nodeCount,
  maxLength: root.length //<-something like this, but I have no idea what to put here
};
like image 681
Glen Pierce Avatar asked Jan 10 '18 02:01

Glen Pierce


1 Answers

This happens because two extra adjacent text nodes are added when we add mark in parent.

So, use node.normalize to wrap the nodes.

like image 168
prerna bhatra Avatar answered Sep 20 '22 01:09

prerna bhatra