JavaScript Document createRange() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.createRange() is an instance method that returns a new Range object (see MDN Document: createRange()). Learn the default collapsed boundaries, how to set start/end points, useful Range helpers, how Ranges relate to Selection, and five try-it labs.

01

Kind

Instance method

02

Args

None

03

Returns

Range

04

Default

Collapsed @ 0

05

Next step

setStart / setEnd

06

Status

Baseline

Introduction

A Range describes a continuous slice of the document — from one boundary point to another. Editors, find-in-page features, and “highlight this word” tools all lean on Ranges.

document.createRange() gives you a fresh Range. MDN: its start and end both begin at offset 0 of the Document on which you called the method. That default is almost never the slice you want, so the next step is always to set real boundaries.

💡
Create → set boundaries → use

1) const range = document.createRange()
2) range.setStart(...) / range.setEnd(...) (MDN)
3) Read text, extract nodes, or add the range to a Selection

MDN Notes: once a Range is created, you need to set its boundary points before you can make use of most of its methods.

Related tutorials: createElement(), createDocumentFragment(), textContent.

Understanding document.createRange()

An instance method on Document (usually called as document.createRange() on the live page document).

  • No parameters — MDN lists none.
  • Return value — a new Range object (MDN).
  • Initial boundaries — start and end at offset 0 of that Document (MDN).
  • Collapsed — start equals end until you widen the range.
  • ConfiguresetStart, setEnd, selectNode, selectNodeContents, and more.
  • Not a visible selection by itself — use the Selection API to show a highlight in the browser UI.

📝 Syntax

General form of Document.createRange (MDN):

JavaScript
createRange()

Parameters

None (MDN).

Return value

The created Range object (MDN).

Exceptions

None listed for createRange() itself on MDN. Boundary methods such as setStart / setEnd can throw if nodes or offsets are invalid.

MDN example

JavaScript
const range = document.createRange();

range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);

⚡ Quick Reference

GoalCode
Create rangeconst range = document.createRange()
Set start / endrange.setStart(node, offset) / range.setEnd(node, offset)
Select element contentsrange.selectNodeContents(el)
Read textrange.toString()
Collapsed?range.collapsed
Show in UIgetSelection().removeAllRanges(); getSelection().addRange(range)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createRange().

Returns
Range

object

Args
none

MDN

Default
doc offset 0

collapsed

Status
Baseline

since 2015

📋 Fresh Range vs configured Range

Right after createRange()After setStart / setEnd
BoundariesOffset 0 of the Document (MDN)Your chosen nodes + offsets
collapsedUsually truefalse if start ≠ end
Useful methodsLimited until set (MDN Notes)toString, extract, surround, …
Visible highlightNoOnly after adding to Selection

Examples Gallery

Examples follow MDN Document: createRange() and practical Range patterns for beginners.

📚 Getting Started

Create a Range and set its boundaries.

Example 1 — MDN: setStart and setEnd

Create a range, then point both ends at a text node.

JavaScript
const p = document.querySelector("#sample");
const text = p.firstChild; // text node: "Hello Range"

const range = document.createRange();
range.setStart(text, 0);
range.setEnd(text, 5);

console.log(range.toString()); // "Hello"
Try It Yourself

How It Works

MDN’s pattern: create the range, then call setStart and setEnd with a node and character (or child) offset.

Example 2 — Default: collapsed at the Document

Inspect the fresh range before you set boundaries.

JavaScript
const range = document.createRange();

console.log(range.startContainer === document); // true (MDN: Document)
console.log(range.startOffset);                 // 0
console.log(range.endOffset);                   // 0
console.log(range.collapsed);                   // true
console.log(range.toString());                  // ""
Try It Yourself

How It Works

MDN: start and end are offset 0 of the Document. Until you move them, collapsed is true and toString() is empty.

📈 Practical Patterns

Select contents, extract nodes, and show a highlight.

Example 3 — selectNodeContents

Select everything inside an element in one call.

JavaScript
const box = document.querySelector("#box");
const range = document.createRange();
range.selectNodeContents(box);

console.log(range.toString()); // all text inside #box
console.log(range.collapsed);  // false (when #box has content)
Try It Yourself

How It Works

selectNodeContents(el) is a convenient alternative to manual setStart / setEnd when you want the whole interior of a node.

Example 4 — extractContents()

Pull the ranged content out into a DocumentFragment.

JavaScript
const p = document.querySelector("#line");
const text = p.firstChild; // "Cut me out"

const range = document.createRange();
range.setStart(text, 0);
range.setEnd(text, 3); // "Cut"

const fragment = range.extractContents();
console.log(fragment.textContent); // "Cut"
console.log(p.textContent);        // " me out"
Try It Yourself

How It Works

extractContents() removes the ranged slice from the live tree and returns it as a fragment — useful for cut / move operations in editors.

Example 5 — Add the Range to Selection

Make the range visible as a browser highlight.

JavaScript
const p = document.querySelector("#highlight");
const range = document.createRange();
range.selectNodeContents(p);

const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

console.log(sel.toString()); // same text as range.toString()
Try It Yourself

How It Works

createRange() alone does not paint a blue selection. Clearing old ranges and calling addRange connects your Range to the UI Selection.

🚀 Common Use Cases

  • Rich-text editors — wrap, delete, or move selected content.
  • Programmatic highlights — select a word and show it via Selection.
  • Find / replace UI — build ranges around matches, then extract or restyle.
  • Measuring textrange.toString() or getBoundingClientRect().
  • Insert at caret — collapsed ranges act like a caret position.
  • Teaching DOM slices — contrast Range with element / fragment APIs.

🧠 How createRange() Works

1

Call createRange()

No args. You get a new Range (MDN).

Create
2

Default boundaries

Start and end at Document offset 0 (MDN).

Collapsed
3

Set start & end

MDN Notes: set boundary points before most methods work usefully.

Configure
4

Use the Range

Read text, extract, wrap, or add to Selection.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • No parameters; returns a Range (MDN).
  • Initial start/end: offset 0 of the Document (MDN).
  • Set boundary points before relying on most Range methods (MDN Notes).
  • A Range is not automatically a visible browser selection.
  • Related: createDocumentFragment(), createElement(), textContent.

Browser Support

Document.createRange() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.createRange()

Create Range objects for DOM selection and editing across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createRange() Wide

Bottom line: Use createRange() to build a Range, set boundaries with setStart/setEnd (or helpers), then read, extract, or add it to Selection.

Conclusion

document.createRange() returns a new Range collapsed at the Document. Follow MDN: set setStart / setEnd (or selectNodeContents), then use the range to read text, extract content, or drive the Selection API.

Continue with createProcessingInstruction(), createTextNode(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Set boundaries right after createRange() (MDN Notes)
  • Prefer selectNodeContents when you want a whole element interior
  • Use range.collapsed to detect caret-like ranges
  • Clear and addRange when you need a visible highlight
  • Work with text nodes carefully when using character offsets

❌ Don’t

  • Assume the default range selects page content (it does not)
  • Expect a blue highlight without the Selection API
  • Pass invalid offsets to setStart / setEnd
  • Confuse Range with DocumentFragment
  • Forget that extractContents mutates the live DOM

Key Takeaways

Knowledge Unlocked

Five things to remember about createRange()

Build DOM Ranges, then set boundaries before using them.

5
Core concepts
📄02

Args

none

MDN
⚖️03

Default

doc @ 0

collapsed
04

Next

setStart/End

MDN
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createRange() returns a new Range whose start and end are both at offset 0 of the Document it was called on. You then set real boundaries with setStart, setEnd, or helpers like selectNodeContents.
No. MDN marks Document.createRange() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A new Range object (MDN). It does not select text in the UI by itself — attach it to a Selection (for example selection.addRange(range)) if you want a visible highlight.
No. createRange() takes no parameters (MDN). Boundaries are configured afterward.
MDN Notes: once a Range is created, you need to set its boundary points before you can make use of most of its methods. The default range is collapsed at the document.
createRange builds a Range you control in code. getSelection() reads (or updates) what the user currently selected. You often create a Range, then add it to the Selection to show a highlight.
Did you know?

Modern browsers also support new Range() as a constructor. For tutorials and older codebases, document.createRange() remains the classic MDN-documented factory — and it always associates the range with that document context.

Next: createTextNode()

Learn how to create Text nodes, append plain text, and escape HTML characters safely.

createTextNode() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful