     document = bounds.ownerDocument
 
     if not contains(bounds, @start)
-      node = bounds
-      while node? and node = firstLeaf(node)
-        if node.nodeType is TEXT_NODE
-          break
-        node = node.nextBranch(bounds, node)
-      @start = node
+      @start = findNode(firstLeaf(bounds), bounds, isTextNode, postFirst)
 
     if not contains(bounds, @end)
-      node = bounds
-      while node? and node = lastLeaf(node)
-        if node.nodeType is TEXT_NODE
-          break
-        node = node.previousBranch(bounds, node)
-      @end = node
+      @end = findNode(lastLeaf(bounds), bounds, isTextNode, postLast)
 
     return null unless @start and @end
 

        throw new DOMException(message, name)

    for node in ancestors(range.startContainer)
      if range.endContainer.nodeType == TEXT_NODE
        endContainer = range.endContainer.parentNode
      else
        endContainer = range.endContainer

    }


# Get all the text Nodes within a Node.
getTextNodes = (root) ->
  text = []
  node = firstLeaf(root)
  while node = findNode(node, root, isTextNode, postFirst)
    text.push(node)
    if node is root then break
    node = postFirst(node)
  return text


# Predicate for checking if a node is a TextNode.
isTextNode = (node) ->
  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 post-order traversal.
postFirst = (node) ->
  if node.nextSibling?
    return firstLeaf(node.nextSibling)
  return node.parentNode


# Return the next Node in a last-to-first-child post-order traversal.
postLast = (node) ->
  if node.previousSibling?
    return lastLeaf(node.previousSibling)
  return node.parentNode


# Find the first leaf node.
firstLeaf = (node) ->
  node = node.firstChild while node.hasChildNodes()
  return node


# Find the last leaf node.
lastLeaf = (node) ->
  node = node.lastChild while node.hasChildNodes()
  return node
