       if node is endContainer and endOffset == 0 then return false
       return true
 
-    # Find the start and end TextNode nodes.
-    start = findNode(startContainer, last, checkNode, preFirst)
-    end = findNode(endContainer, first, checkNode, preLast)
+    # Find the start and end TextNode.
+    checkStart = (node) ->
+      if checkNode(node) then start = node
+      return not (start or node is last)
+
+    checkEnd = (node) ->
+      if checkNode(node) then end = node
+      return not (end or node is start)
+
+    someNode(startContainer, checkStart)
+    someNode(endContainer, checkEnd, preLast)
 
     return new NormalizedRange({commonAncestor, start, end})
 

  return node.nodeType is TEXT_NODE


# Find the first Node in [start, end] (by step(node)) that passes the check.
findNode = (start, end, check, step) ->
  node = start
  node = step(node) while not (pass = check(node)) and node isnt end
  if pass then return node else return null


# Return the next Node in a first-to-last-child pre-order traversal.
preFirst = (node) ->
  if node.firstChild?

    if fn(node) then result.push(node)
    return node isnt last

  someNode(root, collect)

  return result

