How to get nodes lying inside a range with javascript?

后端 未结 9 2086
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 03:59

I\'m trying to get all the DOM nodes that are within a range object, what\'s the best way to do this?

var selection = window.getSelection(); //what the user          


        
9条回答
  •  执念已碎
    2020-11-29 04:35

    The getNextNode will skip your desired endNode recursively if its a parent node.

    Perform the conditional break check inside of the getNextNode instead:

    var getNextNode = function(node, skipChildren, endNode){
      //if there are child nodes and we didn't come from a child node
      if (endNode == node) {
        return null;
      }
      if (node.firstChild && !skipChildren) {
        return node.firstChild;
      }
      if (!node.parentNode){
        return null;
      }
      return node.nextSibling 
             || getNextNode(node.parentNode, true, endNode); 
    };
    

    and in while statement:

    while (startNode = getNextNode(startNode, false , endNode));
    

提交回复
热议问题