All questions

Text Between Nodes

Premium

Text Between Nodes

Given a root element and two element nodes inside it — startNode and endNode — collect the text that appears between them when you read the document top to bottom. "Between" means in document order: flatten the whole subtree into the order a reader would scan it, then gather every piece of text that comes after startNode and before endNode. The two boundary elements are descendants of root, and startNode always comes before endNode in document order.

Signature

function textBetweenNodes(
  root: Element,        // the subtree to search within
  startNode: Element,   // exclusive lower boundary (an element)
  endNode: Element      // exclusive upper boundary (an element)
): string;              // concatenated text strictly between the boundaries

The boundaries are element nodes. You return the concatenation of all text nodes that fall strictly between them in document order — nothing from inside or before startNode, nothing from inside or after endNode.

Examples

const root = document.createElement('div');
root.innerHTML = '<a>start</a>middle<b>end</b>';
const a = root.querySelector('a');
const b = root.querySelector('b');

textBetweenNodes(root, a, b); // => 'middle'
// Text NESTED inside elements between the boundaries still counts.
root.innerHTML = '<a>start</a>X<span>Y<i>Z</i></span><b>end</b>';
textBetweenNodes(root, root.querySelector('a'), root.querySelector('b'));
// => 'XYZ'   (the nested Y and Z read between a and b in document order)

Notes

  • Boundaries are elements; the payload is text nodes. You skip the text inside startNode and endNode themselves — only what lies between them counts.
  • Document order, not sibling order. A pre-order flatten of root defines "between." Text in a different branch of the tree still counts if it reads between the boundaries.
  • Different depths are fine. startNode and endNode may live at different nesting levels. The answer is defined by reading order, not by tree siblings.
  • Adjacent boundaries. If nothing reads between them, return the empty string ''.
  • Whitespace is text. Whitespace-only text nodes are real text and are preserved exactly, in order.
  • Concatenation order is document order. Fragments are joined in the order they appear when reading top to bottom.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium