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?
The basic concept of selection is Range, that is essentially a pair of “boundary points”: range start and range end. A Range object is created without parameters: let range = new Range(); Then we can set the selection boundaries using range.
A Selection object represents the range of text selected by the user or the current position of the caret. To obtain a Selection object for examination or manipulation, call window. getSelection() .
The range() function creates the range of specified objects and sets the boundary before using its methods. This section provides a detailed direction on how to use the range() method to create a range in JavaScript. The range() function creates the difference between the lower and upper value in an index.
getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.
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 Range
s 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:
Selection
may contain multiple Ranges. However, the only major browser to support this currently is Firefox.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With