-1

Right now I am trying to get the range of an selection inside of an div. The problem: When I have a div like this:

<div> Lorem <p> ipsum dolor sit amet, <b> consetetur <b> sadipscing elitr, <i>sed</i> diam nonumy eirmod tempor invidunt </p> ut l </div>

and am selecting a area that includes multiple of these inner HTML nodes I get something like this: startOffset: 10, endOffset: 2 instead of startOffset: 10, endOffset: 12.

Essentially I want to get the selection ignoring the HTML inside the div.

1 Answers1

0

I assume that's what you want.

document.addEventListener("click", function () {
  if (window.getSelection) {
    let text=window.getSelection().toString();
    let range=window.getSelection().getRangeAt(0);
    console.log(range.startContainer.textContent, range.startOffset, range.endOffset)
  }
}

, false);
<div> Lorem
  <p> ipsum dolor sit amet, <b> consetetur <b> sadipscing elitr, <i>sed</i> diam nonumy
                    eirmod tempor
                    invidunt </p> ut l </div>
CanUver
  • 1,716
  • 1
  • 5
  • 18