JSFiddle - React, Tailwind, and code Playground

Text in Range FB Optimized Solution 2

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;

	var stop = false;
	while (cur !== null) {
  	while (cur.nextSibling !== null) {
      cur = cur.nextSibling;
      traverse(cur);
      if (stop) return text;
    }
    cur = cur.parentNode;
	}

	function traverse(cur) {
    if (cur.nodeType === 3) {
      text += cur.nodeValue;
    } else {
			for (var i = 0; i < cur.childNodes.length; i++) {
      	traverse(cur.childNodes[i]);
        if (stop) return;
      }
    }
    if (cur === b) {
    	stop = true;
      return;
		}
	}

  return text;
}

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