JSFiddle - React, Tailwind, and code Playground
textInRange
by Ttt Yyy
HTML
<div>
<div>
<span id="start"> Hello </span>
<div>
<img src="http://placehold.it/100x75" />
</div>
<div>
<span> include me </span>
</div>
<span id="end">World</span>
<span>dont include me</span>
</div>
<br />
<div id="console" />
JavaScript
const getHighlightedText = (nodeA, nodeB) => {
let text = ''
let current = nodeA;
while(current !== nodeB) {
if(current.nodeType === 3) {
text += current.nodeValue;
}
if(current.firstChild !== null) {
current = current.firstChild;
} else {
while(current.nextSibling === null) {
current = current.parentNode;
}
current = current.nextSibling;
}
}
text += current.nodeValue;
return text;
}
let node1 = document.getElementById('start').firstChild;
let node2 = document.getElementById('end').firstChild;
let result = getHighlightedText(node1, node2);
let console = document.getElementById('console');
console.innerHTML = `Result: ${result}`