JSFiddle - React, Tailwind, and code Playground

Text In Range FB Optimized Solution 1

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>don't include me</span>
  </div>
  <br />
  <div id="console" />

JavaScript

function getHighlightedText(a, b) {
	var text = a.nodeValue;
  var cur = a;
  while (cur !== b) {
    if (cur.firstChild !== null) {
    	cur = cur.firstChild;
		} else {
    	while (cur.nextSibling === null) {
      	cur = cur.parentNode;
      }
      cur = cur.nextSibling;
		}
    if (cur.nodeType === 3) {
	    text += cur.nodeValue;
    }
	}
  return text;
}

document.getElementById('console').innerHTML = 'Result: ' + 
  getHighlightedText(
    document.getElementById('start').firstChild,
    document.getElementById('end').firstChild
  );