开发者

Splitting node content in JavaScript DOM

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?&l开发者_C百科t;/strong>

How would I go about doing this?


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


See the method Text.splitText.


Not sure if this helps you, but this is what I came up with...

Pass the function an element and a node tag name string you wish to move up to.

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

<script type="text/javascript">


  function findParentNode(element,tagName){
    tagName = tagName.toUpperCase();
    var parentNode = element.parentNode;
    if (parentNode.tagName == tagName){
    //Erase data up to and including the node name we passed
    console.log('Removing node: '+parentNode.tagName+'  DATA: '+parentNode.firstChild.data);
    parentNode.firstChild.data = '';
    return parentNode;
}
    else{
    console.log('Removing node: '+parentNode.tagName+'  DATA: '+parentNode.firstChild.data);
    //Erase the first child's data (the first text node and leave the other nodes intact)
    parentNode.firstChild.data = '';
    //Move up chain of parents to find the tag we want. Return the results so we can do things with it after
    return findParentNode(parentNode, tagName)
}
  }
var ourNode = document.getElementById("span");

alert(findParentNode(ourNode,'strong').innerHTML);


</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜