JavaScript Selection API

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • Selection sel = window.getSelection();
  • Selection sel = document.getSelection(); // equivalent to the above
  • Range range = document.createRange();
  • range.setStart(startNode, startOffset);
  • range.setEnd(endNode, endOffset);

Parameters

ParameterDetails
startOffsetIf the node is a Text node, it is the number of characters from the beginning of startNode to where the range begins. Otherwise, it is the number of child nodes between the beginning of startNode to where the range begins.
endOffsetIf the node is a Text node, it is the number of characters from the beginning of startNode to where the range ends. Otherwise, it is the number of child nodes between the beginning of startNode to where the range ends.

Remarks

The Selection API allows you to view and change the elements and text that are selected (highlighted) in the document.

It is implemented as a singleton Selection instance that applies to the document, and holds a collection of Range objects, each representing one contiguous selected area.

Practically speaking, no browser except Mozilla Firefox supports multiple ranges in selections, and this is not encouraged by the spec either. Additionally, most users are not familiar with the concept of multiple ranges. As such, a developer can usually only concern themselves with one range.



Got any JavaScript Question?