Browser / DOM - Range - defining a sequence of characters


A range represent a sequence of content at the character level within a node tree.

They are used in editing for


Below we will define the range that represents the olor sit ame

<p>Lorem ipsum dolor sit <em>amet, consectetur</em> adipiscing elit</p>
  • The javascript that select the p and em node used later to define the start and end character of the range
let p = document.querySelector("p");
let em = document.querySelector("em");
  • Creating the range with the text node of p and em
let range = new Range(),
      pTextNode = p.childNodes[0], 
      emTextNode = em.firstChild;
range.setStart(pTextNode, 13); // from the 13 characters of the p element
range.setEnd(emTextNode, 3); // until the third character of em
  • Select the text to show the range
var sel = window.getSelection();
  • Result:


A range has two associated boundary points

  • a start
  • and end.

Boundary point

A boundary point consists:

  • of a node (generally a text node)
  • and an offset (a non-negative integer) between 0 and the node length:
    • in a text node, it represents the position of the character in the content.
    • in a container node, it represents the childs (?)


A collapsed Range is empty and specifies only a single-point in the DOM tree.

Discover More
How to select text dynamically in a Browser with Javascript? The window Selection Object explained

How to manipulate the selection made by a mouse or with the keyboard in a browser
Devtool Chrome Event Listener
What is the selectstart DOM event with examples and howto's in Javascript?

selectstart is a selection event that occurs when the user agent (the browser used by the user mostly) is to associate a new range to a selection object Note that when the user clicks on: a text,...

Share this page:
Follow us:
Task Runner