Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Table of contents
Range Methods
Implementation of Range Methods
Selection Methods
Implementation of Selection Methods
Selection Events
Frequently Asked Questions
What is a JavaScript range object?
In a coding interview, is JavaScript important?
In JavaScript, what does an object mean?
Is JavaScript synchronised or asynchronous?
Last Updated: Mar 27, 2024

JavaScript Selection and Range

Roadmap to SDE career at Amazon
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM


Do you know Javascript can know if you select text on a web page, retrieve the current selection, choose or deselect wholly or partially? Additionally, JavaScript can manipulate this selected or deselected text in the document and form fields.

This blog post will highlight how JavaScript can handle such text selection on a web page and the various methods, properties, and constructors.

After reaching the end of this post, you will clearly understand the basic concepts of Selection and Range in JavaScript.


The Range is the most fundamental idea in selection. It is just a pair of border points and can be defined as “range start” and “range end.” We use the method "Document.createRange()" to create a range. We can use the "getRangeAt()" method of the Selection object and the "caretRangeFromPoint()" function of the Document object to retrieve Range objects.

You can transform a selection to a Range as soon as the user selects (part of) the text on an HTML page. You can copy or delete it or replace it with another text or even a bit of HTML. Typically, a user will only select one range at a time; however, it is possible to select numerous ranges (e.g., using the Control key).


Various properties of JavaScript Range are as follows:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job


To create a range object, we use the following constructor:

  • Range(): Returns a Range object whose start and endpoints are the global Document.

Range Methods

  1. Range.compareBoundaryPoints()
    Compare the Range's boundary points to those of another Range.
  2. Range.compareNode()
    Returns a constant indicating whether the Node is in the range before, after, inside, or around it.
  3. Range.comparePoint()
    Returns -1, 0 or 1 depending on whether the point is inside, outside, or before the Range.
  4. Range.collapse()
    The Range collapsed to one of its boundary points.
  5. Range.cloneContents()
    Returns a DocumentFragment that duplicates a Range's nodes.
  6. Range.cloneRange()
    Returns a Range object with the same boundary points as the original Range.
  7. Range.createContextualFragment()
    This method creates a DocumentFragment from a specified code string.
  8. Range.deleteContents()
    This method removes a Range's contents from the Document.
  9. Range.detach()
    Allows you to stop using the Range to enhance your performance.
  10. Range.extractContents()
    This method moves the contents of a Range into a DocumentFragment from the document tree.
  11. Range.getBoundingClientRect()
    This is the union of all the rectangles returned by range. Returns a DOMRect object that boundaries the whole contents of the range.getClientRects().
  12. Range.getClientRects()
    This method returns a list of DOMRect objects containing the aggregated results of "Element.getClientRects()" for all items in the Range.
  13. Range.isPointInRange()
    Returns a boolean indicating whether or not the specified point is within the Range.
  14. Range.insertNode()
    Adds a Node at the beginning of a Range.
  15. Range.intersectsNode()
    If the specified node intersects the Range, this method returns a boolean value.
  16. Range.selectNode()
    Sets the range in which the Node and its contents will be contained.
  17. Range.selectNodeContents()
    Sets the Range to hold a Node's contents.
  18. Range.setEnd()
    This method sets the Range's end position.
  19. Range.setStart()
    This method sets the Range's start position.
  20. Range.surroundContents()
    The contents of a Range are moved to a new Node.
  21. Range.toString()
    The Range's text is returned when this function is called.

Implementation of Range Methods

Different methods of Javascript range can be implemented to manipulate the selection. Below is an example of the implementation of range methods.

<!--- JavaScript Range Methods Range.deleteContents(), Range.insertNode(), Range.extractContents() --->
<title>Range methods</title>
<p id="p">Example text: <i> this is italic</i> and <b> this is bold.</b></p>
<p id="result"></p>
  let range = new Range();

  // the methods are implemented in the prototype of the Range object
    let methods = {
        deleteContents() {
            document.getElementById("result").innerHTML = "deleteContents()";
        extractContents() {
            var txt = range.extractContents();
        insertNode() {
            document.getElementById("result").innerHTML = "insertNode() called!";
        surroundContents() {
            var newnode = document.createElement("b");
            try {
            } catch(e) {
            document.getElementById("result").innerHTML = e;}
        resetExample() {
        p.innerHTML = `Example text: <i> this is italic</i> and <b> this is bold.</b>`;
        result.innerHTML = "";

        range.setStart(p.firstChild, 2);
        range.setEnd(p.querySelector('b').firstChild, 3);


  for(let m in methods) {
    document.write(`<div><button onclick="methods.${m}()">${m}</button></div>`);


In the above example we have implemented the deleteContents(), extractContents, insertNode(), surroundNode() methods. The output shows that the “insertNode()” method has inserted the text “insertedNODE” into the original text. Similarly, we can implement the remaining methods as well.

You can practice by yourself with the help of Online Javascript Compiler for better understanding.


Selection object represents the user-selected text range or the caret's current position. A user can choose from left to right (in document order) or right to left (reverse of document order). The anchor indicates where the user started the selection, whereas the focus indicates where the user finished it. When you use a desktop mouse to create a selection, the anchor is where you press the mouse button, and the focus is where you let go of the mouse button.
We call the window.getSelection() function to get a Selection object for examining or manipulating it.


Various properties of JavaScript Selection are as follows:

Selection Methods

There are various built-in methods for Selection. The methods are as follows:

  1. Selection.addRange()
    We use this method to add an item to the selection as a Range object.
  2. Selection.collapse()
    This method reduces the current selection to a single point.
  3. Selection.collapseToEnd()
    The selection is collapsed to the end of the last range in the selection.
  4. Selection.collapseToStart()
    The selection is collapsed to the beginning of the first range in the selection.
  5. Selection.containsNode()
    Indicates whether or not a particular node is included in the selection.
  6. Selection.deleteFromDocument()
    The content of the selection is removed from the document.
  7. Selection.extend()
    This method sets the selection's emphasis to a specific location.
  8. Selection.getRangeAt()
    Returns a Range object that represents one of the current ranges.
  9. Selection.modify()
    The current selection has been changed.
  10. Selection.removeRange()
    A range is removed from the selection.
  11. Selection.removeAllRanges()
    All ranges are removed from the option.
  12. Selection.selectAllChildren()
    The children of the specified node are added to the selection.
  13. Selection.setBaseAndExtent()
    This method sets the selection to a range that includes all or parts of two DOM nodes and any content between them.
  14. Selection.toString()
    Returns the string that the selected object is presently representing, i.e. the currently selected text.

Implementation of Selection Methods

<!-- JavaScript Selection.removeAllRanges() and Selection.addRange() methods -->
<p id="text">Lorem <i>ipsum</i> dolor <i>amet</i> consectetur <i>adipiscing elit</i></p>
From <input id="start" type="number" value=1> to <input id="end" type="number" value=4>
<button id="btn">Select</button>
    btn.onclick = () => {
        // define range
        let range = new Range();
        // set start and end
        range.setStart(text, start.value);
        range.setEnd(text, end.value);
        // select range


Here, the text “Lorem” gets the offset 0, and  “ipsum” gets 1. So the selection ranges from “ipsum” to “amet.” We have implemented the methods “Selection.removeAllRanges()” and “Selection.addRange().”

Selection Events

There are events taking place to keep track of the selection process:

  • elem.onselectstart: When a selection begins on an element only (or inside it). For example, when the user hits the mouse button, the cursor begins to move. The start of the selection is cancelled if the default action is disabled. As a result, beginning a selection from this element is no longer feasible, but the element remains selectable. The visitor only needs to begin the choosing process from somewhere else.
  • document.onselectionchange: When a selection changes or starts, "document.onselectionchange" is called. Please note that this handler can only be configured on a document, and it will track all selections made within it.

Frequently Asked Questions

What is a JavaScript range object?

The start and endpoints of a Range object define it. An element and its position define a point. The position specifies a character position within the element if the element solely includes text content (TextNode, CDATASection, or CommentNode), otherwise, it specifies the index of a child of the element.


In a coding interview, is JavaScript important?

Interviewers are evaluating you on your coding and problem-solving abilities. As a result, they will urge you to choose the programming language you are most familiar with and fluent in. If you know and can code in JavaScript, it's the most significant language to utilise in an interview.


In JavaScript, what does an object mean?

An object is a separate entity having properties and a type in JavaScript. As an example, consider a cup. A cup is a property-based object. A cup has a colour, a pattern, a weight, and a material. JavaScript objects can have properties that specify their qualities in the same way.


Is JavaScript synchronised or asynchronous?

JavaScript is a highly flexible single-threaded, non-blocking, asynchronous, concurrent programming language. Wait a minute, did that say single-threaded and asynchronous all at once? If you're familiar with the term "single-threaded," you probably think of synchronous operations.


This article extensively discussed JavaScript Selection and Range and various properties and methods associated with them. We illustrated these two concepts by implementing them in HTML. The basic concepts of JavaScript Selection and Range will help you manipulate text selections in web programming. 

We hope that this blog has helped you enhance your JavaScript Selection and Range knowledge. If you want to learn more, check out our articles on "Javascript BOM," "Event Loop in JavaScript," "Regular Expressions in JavaScript," and "JavaScript DOM." Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations and much more!

Happy Reading!


Previous article
Mutation Observer in JavaScript
Next article
Event Loop in JavaScript
Live masterclass