title: How to get nodes lying inside a range with javascript?
body: <p>I'm trying to get all the DOM nodes that are within a range object, what's the best way to do this?</p>
  
  <pre><code>var selection = window.getSelection(); //what the user has selected
  var range = selection.getRangeAt(0); //the first range of the selection
  var startNode = range.startContainer;
  var endNode = range.endContainer;
  var allNodes = /*insert magic*/;
  </code></pre>
  
  <p>I've been been thinking of a way for the last few hours and came up with this:</p>
  
  <pre><code>var getNextNode = function(node, skipChildren){
      //if there are child nodes and we didn't come from a child node
      if (node.firstChild &amp;&amp; !skipChildren) {
          return node.firstChild;
      }
      if (!node.parentNode){
          return null;
      }
      return node.nextSibling 
          || getNextNode(node.parentNode, true);
  };
  
  var getNodesInRange = function(range){
      var startNode = range.startContainer.childNodes[range.startOffset]
              || range.startContainer;//it's a text node
      var endNode = range.endContainer.childNodes[range.endOffset]
              || range.endContainer;
  
      if (startNode == endNode &amp;&amp; startNode.childNodes.length === 0) {
          return [startNode];
      };
  
      var nodes = [];
      do {
          nodes.push(startNode);
      }
      while ((startNode = getNextNode(startNode)) 
              &amp;&amp; (startNode != endNode));
      return nodes;
  };
  </code></pre>
  
  <p>However when the end node is the parent of the start node it returns everything on the page. I'm sure I'm overlooking something obvious? Or maybe going about it in totally the wrong way.</p>
  
  <p><a href="https://developer.mozilla.org/en/DOM/range" rel="noreferrer">MDC/DOM/range</a></p>