Collect text from all DOM nodes between two given nodes
Create a function getTextBetweenTwoNodes that retrieves all the text content found in the DOM between two specified nodes, node1 and node2. The function should traverse the DOM tree, collecting text from text nodes that are located between these two nodes, and return an array of these text snippets. MDN’s Range and TreeWalker docs are useful references for walking text between two DOM nodes.
The function should consider a depth-first search approach to navigate through the DOM elements, ensuring that all text nodes between the two specified nodes are included. It’s important to handle various edge cases, such as when the nodes are nested at different levels or when there’s no direct sibling relationship between them.
Function Signature:
function getTextBetweenTwoNodes(node1: Node, node2: Node): string[]
Example Usage:
const node1 = document.getElementById('start');
const node2 = document.getElementById('end');
const textsBetween = getTextBetweenTwoNodes(node1, node2);
console.log(textsBetween); // Output: Array of text snippets between node1 and node2
This utility can be particularly useful for web scraping, automated testing, or any scenario where understanding the text content between two DOM elements is required.