Alex Rivera | Logout

Splitting node content in JavaScript DOM

Asked 2011-08-30T01:37:48.767
12

I have a scenario where I need to split a node up to a given ancestor, e.g.

<strong>hi there, how <em>are <span>you</span> doing</em> today?</strong>

needs to be split into:

<strong>hi there, how <em>are <span>y</span></em></strong>

and

<strong><em><span>ou</span> doing</em> today?</strong>

How would I go about doing this?

Edit
Report

1 Answer

10

Here is a solution that will work for modern browsers using Range. Something similar could be done for IE < 9 using TextRange, but I use Linux so I don't have easy access to those browsers. I wasn't sure what you wanted the function to do, return the nodes or just do a replace inline. I just took a guess and did the replace inline.

function splitNode(node, offset, limit) {
  var parent = limit.parentNode;
  var parentOffset = getNodeIndex(parent, limit);

  var doc = node.ownerDocument;  
  var leftRange = doc.createRange();
  leftRange.setStart(parent, parentOffset);
  leftRange.setEnd(node, offset);
  var left = leftRange.extractContents();
  parent.insertBefore(left, limit);
}

function getNodeIndex(parent, node) {
  var index = parent.childNodes.length;
  while (index--) {
    if (node === parent.childNodes[index]) {
      break;
    }
  }
  return index;
}

Demo: jsbin

It expects a TextNode for node, although it will work with an Element; the offset will just function differently based on the behavior of Range.setStart

answered 2011-08-30T02:50:15.120

Your Answer