javascripthtmlgetselection

window.getSelection().baseOffset is wrong


If you select any text below beginning at the first character H, it will say the baseOffset of the selection is 5. In my real-life case it says 7. How do I correct this?

setInterval(()=>{
  console.log(window.getSelection().baseOffset);
}, 250);
<!DOCTYPE html>
<html>
  <body>
    <div id='main'data-alignment="center">
    Hello World!
    </div>
  </body>
</html>


Solution

  • The result is correct, you have exactly 5 space characters between the end of <div id='main'data-alignment="center"> and the H, these will be counted as offset.

    To avoid that, you can wrap your TextNode in a <span> element so that there is no offset.

    Also, baseOffset is still not in the official specs, better use anchorOffset which I think does approximately the same thing (but is supported in all browsers).

    document.onselectionchange = ()=>{
      console.log(window.getSelection().anchorOffset);
    };
    <!DOCTYPE html>
    <html>
      <body>
        <div id='main'data-alignment="center">
          <span>Hello World!</span>
        </div>
      </body>
    </html>