28

I wanted to know the difference between the range and the selection object in JavaScript.

It appears to me that you could get the same functionality out of either of these two. In which case are there are any specific circumstances where you know which of the two to use?

Gunner4Life
  • 736
  • 1
  • 8
  • 18

1 Answers1

38

The fundamental difference is that a Selection represents the user's selection, while Range represents a continuous part of a document independently of any visual representation. A Selection can (almost) be expressed in terms of zero, one or more Ranges but Ranges can also be created and modified completely independently of the selection.

There is some overlap in functionality: for example, Selection's deleteFromDocument() is equivalent to calling deleteContents() on all of its component Ranges, and you can get the boundaries of the most recently selected Range in the selection using the anchorNode, anchorOffset, focusNode and focusOffset properties. However, there are some crucial differences:

  • A Selection may contain multiple Ranges. However, the only major browser to support this currently is Firefox.
  • A Selection may be "backwards", by which I mean that the end boundary of the selection (represented by focusNode and focusOffset) may occur earlier in the document than the start boundary (anchorNode and anchorOffset). A Range has no direction.
  • toString() works differently. In most browsers (although notably not IE 9), calling toString() on a Selection object returns only the visible text that is selected, while calling toString() on a Range will return a concatenation of all text nodes within the range, including those within <script> elements and elements hidden via CSS.
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • I can't see much difference in toString method result. It's printing out the same results for both selection and range object. – Param Singh Sep 09 '18 at 07:35
  • @ParamSingh: I think that may still vary depending on browser. See http://jsbin.com/buhuvuworu/edit?html,js,output in Chrome, for example. – Tim Down Sep 10 '18 at 14:22
  • I made a [demo](https://jsfiddle.net/6z1k2tjr/) for demonstrating the dependency vs independency of visual representation of selection vs range, respectively. – OfirD Dec 15 '20 at 22:49
  • the big difference is that Selection.toString() will preserve/insert whitepace between elements wheras Range.toString() just concatenates text nodes. This means that text nodes from within sibling elements will be concatenated with no extra whitespace. – Gabe O'Leary Jan 29 '22 at 00:43