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

后端 未结 3 761
南方客
南方客 2021-01-31 08:41

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

var a = document.getSelection()

I get an object with four properties :

  1. anchorNod
相关标签:
3条回答
  • 2021-01-31 09:20

    I have been building out a feature that requires nested contenteditable elements. When debugging I noticed that baseNode and extentNode are NOT just aliases. I am trying to find documentation on them since they are not in MDN. But based on this screenshot I wouldn't assume they are just aliases (in Chrome):

    0 讨论(0)
  • 2021-01-31 09:29

    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, baseNode is alias for anchorNode, extentNode for focusNode

    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.

    0 讨论(0)
  • 2021-01-31 09:41

    I'm by no means an expert, but by experimenting it seems to me that the anchorNode is the node the selection started on and focusNode the one where it ended (presumably because it has focus once the selection is over).

    baseNode seems to be the same as anchorNode and extentNode the same as baseNode, only that they don't exist in Firefox, only in Chrome.

    0 讨论(0)
提交回复
热议问题