JavaScript Document caretPositionFromPoint() Method

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

What You’ll Learn

document.caretPositionFromPoint() is an instance method that maps viewport coordinates to a text caret position. Learn the CaretPosition return value (offsetNode, offset), the shadowRoots option, when it returns null, MDN’s click-to-split example, and the caretRangeFromPoint fallback.

01

Kind

Instance method

02

Args

x, y, options

03

Returns

CaretPosition

04

Fields

offsetNode

05

Shadow

shadowRoots

06

Status

Baseline 2025

Introduction

When a user clicks on text, you often need to know which character they clicked nearest to—not just which element. Rich text editors, custom selection tools, and inline formatting all depend on mapping pointer coordinates to a DOM text offset.

MDN: Document.caretPositionFromPoint(x, y) returns a CaretPosition object containing the DOM node, along with the caret and caret’s character offset within that node. Coordinates are viewport-relative (like clientX / clientY from a mouse event).

💡
Beginner tip

Use e.clientX and e.clientY from a click event directly. Always check for null — clicks on empty margins or invalid coordinates may not yield a caret position.

Related tutorials: nodeType, textContent, append(), Document constructor.

Understanding document.caretPositionFromPoint()

An instance method on the page’s document object (CSSOM View Module).

  • Input — horizontal and vertical coordinates in the viewport (MDN).
  • OutputCaretPosition with offsetNode and offset, or null.
  • Text nodesoffset is a character index in the text node.
  • Element nodesoffset may be a child index (MDN shadow example).
  • shadowRoots — optional array to resolve positions inside supplied shadow trees (MDN).
  • Fallback — older browsers may only have non-standard document.caretRangeFromPoint() (MDN).

📝 Syntax

General forms of Document.caretPositionFromPoint (MDN):

JavaScript
caretPositionFromPoint(x, y)
caretPositionFromPoint(x, y, options)

Parameters

  • x — horizontal coordinate of a point (MDN).
  • y — vertical coordinate of a point (MDN).
  • options (optional) — may include:
    • shadowRoots — array of ShadowRoot objects for shadow DOM resolution (MDN).

Return value

A CaretPosition object or null (MDN).

When null is returned (MDN)

  • No viewport associated with the document.
  • x or y are negative or outside the viewport region.
  • Coordinates indicate a point where no text insertion point could be inserted.

Common patterns

JavaScript
// From a click event
paragraph.addEventListener("click", (e) => {
  const pos = document.caretPositionFromPoint(e.clientX, e.clientY);
  if (!pos) return;
  console.log(pos.offsetNode, pos.offset);
});

// With shadow DOM
document.caretPositionFromPoint(x, y, { shadowRoots: [shadow] });

// Fallback for older WebKit
if (document.caretPositionFromPoint) {
  pos = document.caretPositionFromPoint(x, y);
} else if (document.caretRangeFromPoint) {
  const range = document.caretRangeFromPoint(x, y);
  // range.startContainer, range.startOffset
}

⚡ Quick Reference

GoalCode
From clickdocument.caretPositionFromPoint(e.clientX, e.clientY)
Text nodepos.offsetNode (nodeType 3)
Char offsetpos.offset
Shadow DOM{ shadowRoots: [shadow] }
Check supporttypeof document.caretPositionFromPoint === "function"
MDN statusBaseline 2025 (Dec 2025)

🔍 At a Glance

Four facts about document.caretPositionFromPoint().

Returns
CaretPosition

or null

Coords
viewport

clientX/Y

Shadow
shadowRoots

optional

Status
baseline

2025

📋 CaretPosition properties

PropertyMeaning
offsetNodeThe DOM node containing the caret (MDN)
offsetCharacter offset in a text node, or child index in an element (MDN)
getClientRect()Bounding rect of the caret (CaretPosition API)

Examples Gallery

Examples follow MDN Document: caretPositionFromPoint(). Click the try-it paragraphs to explore caret positions interactively.

📚 Getting Started

Read caret position from pointer coordinates.

Example 1 — Basic click: get offsetNode and offset

Map a click on a paragraph to its caret position (MDN pattern).

JavaScript
paragraph.addEventListener("click", (e) => {
  const pos = document.caretPositionFromPoint(e.clientX, e.clientY);
  if (!pos) return;

  console.log({
    nodeName: pos.offsetNode.nodeName,
    nodeType: pos.offsetNode.nodeType,
    offset: pos.offset
  });
});
Try It Yourself

How It Works

For text nodes, nodeType === 3 and offset is the character index nearest the click.

Example 2 — Feature detect with caretRangeFromPoint fallback

MDN: use the standard API first, then the WebKit fallback.

JavaScript
function getCaretAtPoint(x, y) {
  if (document.caretPositionFromPoint) {
    const pos = document.caretPositionFromPoint(x, y);
    return pos
      ? { node: pos.offsetNode, offset: pos.offset, api: "caretPositionFromPoint" }
      : null;
  }
  if (document.caretRangeFromPoint) {
    const range = document.caretRangeFromPoint(x, y);
    return range
      ? { node: range.startContainer, offset: range.startOffset, api: "caretRangeFromPoint" }
      : null;
  }
  return null;
}
Try It Yourself

How It Works

Both APIs expose the same logical caret, but property names differ (offsetNode vs startContainer).

📈 Practical Patterns

Null handling, shadow DOM, and MDN’s split-text demo.

Example 3 — Returns null for invalid coordinates

MDN: negative or out-of-viewport coordinates yield null.

JavaScript
const inside = document.caretPositionFromPoint(100, 100);
const negative = document.caretPositionFromPoint(-1, -1);

console.log(inside !== null);   // true (if point is over text)
console.log(negative === null); // true (MDN)
Try It Yourself

How It Works

Always guard with if (!pos) return before reading offsetNode.

Example 4 — shadowRoots option (MDN)

Pass shadow roots so clicks inside shadow DOM resolve to inner nodes.

JavaScript
const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
shadow.innerHTML = "<span>Shadow text</span>";

// Without shadowRoots — may remap to host
const outer = document.caretPositionFromPoint(x, y);

// With shadowRoots — resolves inside shadow tree (MDN)
const inner = document.caretPositionFromPoint(x, y, {
  shadowRoots: [shadow]
});
Try It Yourself

How It Works

MDN: undisclosed shadow positions remap to the shadow host unless you supply the root in shadowRoots.

Example 5 — MDN: split text and insert <br> at caret

Click a paragraph to split its text node at the caret offset and insert a line break.

JavaScript
function insertBreakAtPoint(e) {
  let textNode, offset;

  if (document.caretPositionFromPoint) {
    const pos = document.caretPositionFromPoint(e.clientX, e.clientY);
    textNode = pos?.offsetNode;
    offset = pos?.offset;
  } else if (document.caretRangeFromPoint) {
    const range = document.caretRangeFromPoint(e.clientX, e.clientY);
    textNode = range.startContainer;
    offset = range.startOffset;
  } else {
    return;
  }

  if (textNode?.nodeType === 3) {
    const replacement = textNode.splitText(offset);
    const br = document.createElement("br");
    textNode.parentNode.insertBefore(br, replacement);
  }
}
Try It Yourself

How It Works

MDN’s official demo: splitText(offset) divides the text node, then a <br> is inserted between the halves.

🚀 Common Use Cases

  • Rich text editors — place the caret where the user clicked.
  • Custom selection — start/end ranges from pointer coordinates.
  • Inline annotations — insert markers at a precise character offset.
  • Click-to-edit — split or wrap text nodes at the clicked position (MDN).
  • Shadow DOM apps — pass shadowRoots for web components.
  • Progressive enhancement — fall back to caretRangeFromPoint on older engines.

🧠 How caretPositionFromPoint() Maps Coordinates

1

Provide x and y

Viewport coordinates, typically clientX / clientY (MDN).

Input
2

Hit-test the document

Browser finds the nearest text insertion point; optional shadowRoots (MDN).

Resolve
3

Build CaretPosition

offsetNode + offset describe the caret (MDN).

Result
4

Return or null

Invalid viewport coords or no insertion point → null (MDN).

📝 Notes

  • MDN: Baseline 2025 (newly available since December 2025).
  • Not Deprecated, Experimental, or Non-standard.
  • Coordinates are viewport-relative, not page/document coordinates.
  • caretRangeFromPoint() is a non-standard fallback (MDN examples).
  • Use shadowRoots when resolving caret positions inside open shadow trees.
  • Related: nodeType, textContent, append().

Browser Support

Document.caretPositionFromPoint() is Baseline 2025 on MDN (newly available since December 2025). Logos use the shared browser-image-sprite.png sprite. Older browsers may only support non-standard caretRangeFromPoint().

Baseline 2025

Document.caretPositionFromPoint()

Standard caret-from-point API — use caretRangeFromPoint as fallback where needed.

Baseline Newly available
Google Chrome Supported (recent)
Yes
Mozilla Firefox Supported (recent)
Yes
Microsoft Edge Supported (recent)
Yes
Apple Safari Check updates
Partial
Opera Chromium mirror
Yes
Internet Explorer Not supported
No
caretPositionFromPoint() 100% supported

Bottom line: Feature-detect document.caretPositionFromPoint and fall back to document.caretRangeFromPoint on older WebKit-based browsers.

Conclusion

document.caretPositionFromPoint(x, y) maps viewport coordinates to a CaretPosition with offsetNode and offset. MDN’s examples show click handlers, shadow DOM options, and splitting text at the caret. Always handle null and provide a caretRangeFromPoint fallback when needed.

Continue with caretRangeFromPoint(), ownerDocument, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use e.clientX / e.clientY from pointer events
  • Check for null before reading offsetNode
  • Feature-detect and fall back to caretRangeFromPoint (MDN)
  • Pass shadowRoots for shadow DOM components
  • Verify nodeType === 3 before calling splitText

❌ Don’t

  • Assume every click returns a caret position
  • Use page coordinates without adjusting for scroll
  • Rely only on elementFromPoint when you need text offsets
  • Forget shadow root disclosure for web components
  • Skip fallback on browsers without Baseline 2025 support

Key Takeaways

Knowledge Unlocked

Five things to remember about caretPositionFromPoint()

Map clicks to text offsets with the standard CaretPosition API.

5
Core concepts
🗂02

Returns

CaretPosition

MDN
🔗03

Fields

offsetNode

offset
👁04

Null

invalid coords

guard
🛡05

Status

baseline

2025

❓ Frequently Asked Questions

It returns a CaretPosition object (or null) for the text insertion point at viewport coordinates x and y — containing the DOM node and character offset within that node (MDN).
No. MDN marks Document.caretPositionFromPoint() as Baseline 2025 (newly available since December 2025). It is not Deprecated, Experimental, or Non-standard.
A CaretPosition with offsetNode and offset properties, or null if there is no viewport, coordinates are invalid, or no insertion point exists at that point (MDN).
caretPositionFromPoint() is the standard method returning CaretPosition. caretRangeFromPoint() is a non-standard WebKit fallback that returns a Range with startContainer/startOffset (MDN).
An optional array of ShadowRoot objects. When supplied, the method can return a caret position inside those shadow trees. Otherwise positions in undisclosed shadow DOM may remap to the shadow host (MDN).
MDN: when there is no viewport, x/y are negative or outside the viewport, or the point has no valid text insertion indicator.
Did you know?

MDN’s official demo uses caretPositionFromPoint() to split a text node at the clicked offset with splitText(), then inserts a <br> — the same pattern rich-text editors use for “click to insert line break” behavior.

Next: caretRangeFromPoint()

Learn the legacy non-standard Range API used as a fallback before Baseline 2025.

caretRangeFromPoint() →

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.

6 people found this page helpful