DOM - Range - Sequence of characters

About

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

They are used in editing for

Example

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();
sel.removeAllRanges();
sel.addRange(range);
  • Result:

Concept

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 (?)

Powered by ComboStrap