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.
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.
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)
startNode and endNode themselves — only what lies between them counts.root defines "between." Text in a different branch of the tree still counts if it reads between the boundaries.startNode and endNode may live at different nesting levels. The answer is defined by reading order, not by tree siblings.''.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.