• constructor

jQuery.Range jQuery.Range


jQuery.Range provides text range helpers for creating, moving, and comparing ranges cross browser. You can get the currently selected range by calling $.Range.current() a new range can be created by passing

  • undefined or null - returns a range with nothing selected
  • HTMLElement - returns a range with the node's text selected
  • Point - returns a range at the point on the screen. The point can be specified like:

    //client coordinates
    {clientX: 200, clientY: 300}
    //page coordinates
    {pageX: 200, pageY: 300}
    {top: 200, left: 300}
  • TextRange a raw text range object.

to the constructor.


An instance of $.Range offers the following methods:

  • clone - clones the range and returns a new $.Range object
  • collapse - clones the range and returns a new $.Range object
  • compare - compares one range to another range
  • end - sets or returns the end of the range
  • move - move the endpoints of a range relative to another range
  • overlaps - returns if any portion of these two ranges overlap
  • parent - returns the most common ancestor element of the endpoints in the range
  • rect - returns the bounding rectangle of this range
  • rects - returns the client rects
  • start - sets or returns the beginning of the range
  • toString - returns the text of the range

Note, that the container returned by start and end can be a text node or cdata section (see node types). It can be checked by comparing the returned elements nodeType with Node.TEXT_NODE or Node.CDATA_SECTION_NODE which you will need to get the element containing the selected text:

var startNode = range.start().container;
if( startNode.nodeType === Node.TEXT_NODE ||
  startNode.nodeType === Node.CDATA_SECTION_NODE ) {
  startNode = startNode.parentNode;


Consider an HTML element like

<div id="text">This is some text</div>`

$.Range can be used like this:

// Get a text range for #text
var range = $('#text').range();

// Move the start 5 characters to the right

// Move the end 5 characters to the left

// Return the range text
range.toString() // is some

// Select the current range

 // get the startOffset of the range and the container
 range.start() //-> { offset: 5, container: HTMLELement }

 //get the most common ancestor element
 var parent = range.parent();

 //select the parent
 var range2 = new $.Range(parent);