javascripthtmlcss

How can I get the selectionOffset relative to the parent element?


If you click on the 'M' the offset should be 6 but because it's inside another element getSelection() returns the offset of that particular element, is it possible to return the offset from the parent span instead ?

l.addEventListener('click', (e)=>{
    console.log(window.getSelection().anchorOffset)
})
body{ background: #1a1d21; font-size: 2em;}
span{color: white}
<span id='l'>begin<span>Middle</span>end</span>


Solution

  • As you have mentioned "because it's inside another element getSelection().anchorOffset returns the offset of that particular element". In other words the offset you're looking for is what you have so far + the length of the text before the target element .

    el.addEventListener('click', e => {
      const anchorNode = window.getSelection().anchorOffset;
      const content = e.currentTarget.textContent.split(e.target.textContent);
      console.log(content[0].length + anchorNode);
    })
    body {
      background: #1a1d21;
      font-size: 2em;
    }
    
    span {
      color: white
    }
    <span id="el">begin<span>Middle</span>end</span>