javascripthtmlgoogle-chromedomdocument

What is anchorNode , baseNode , extentNode and focusNode in the object returned by document.getSelection?


If I make a selection in a html page and I do :

var a = document.getSelection()

I get an object with four properties :

  1. anchorNode
  2. baseNode
  3. extentNode
  4. focusNode

the values of first three is the same i.e. the text that I have selected but how are they different and which one to use?


Solution

  • According to MDN

    selection.anchorNode - returns the Node in which the selection begins.

    selection.focusNode - returns the Node in which the selection ends.

    because there were debates on naming:

    Note: references to both baseNode and extentNode have been removed from the MDN page.

    The following is beyond the scope of this question, but I'll post this anyway, as I found selection to be a tricky part in some scenarios.

    Take a look at this example:

    <p>ab12<sup>3</sup>4567890 !</p>
    

    Let's say we've made selection "1234567890". I've made a picture to explain where anchor and focus nodes and offsets are.

    window.getSelection