CKTIS / JavaScript
Range: common ancestor, offsets, and collapsed state
Read a DOM range’s boundary points, find their closest shared node, and tell whether both boundaries refer to the exact same point.
Version: Current web platform; runtime support varies
Syntax
range.commonAncestorContainer
range.startOffset
range.endOffset
range.collapsedRange is a DOM interface, not part of ECMAScript 2024. Support for these properties depends on the host’s DOM implementation, not its ECMAScript edition. Do not assume they exist in a runtime without a DOM. Each boundary is a pair: a node and an offset. Read startOffset with startContainer and endOffset with endContainer.
An offset is a zero-based position, not the index of the last included character. In a CharacterData node such as Text, it counts UTF-16 code units before the boundary, not user-perceived characters. In a container such as an Element, it counts direct child nodes before the boundary, including text and comments, as in childNodes. Offset 0 is before the first unit or child; the full length is after the last one.
commonAncestorContainer returns the deepest node that is an ancestor of, or is itself, each boundary container. If both containers are the same node, that node is returned, even if it is a Text node. collapsed is true only when both boundaries have the same node and offset. Equal offsets in different nodes are not enough.
Range.commonAncestorContainer/startOffset/endOffset/collapsed names four read-only instance properties; startOffset, endOffset, and collapsed are inherited from AbstractRange. Use setStart() and setEnd() to move the boundaries. collapse(true) collapses to the start; collapse(false) or collapse() collapses to the end. A Range is live: DOM edits can adjust its boundaries.
Examples
<!doctype html>
<meta charset="utf-8">
<title>DOM Range boundary points</title>
<script>
{
const container = document.createElement('div');
const text = document.createTextNode('A😀B');
container.appendChild(text);
const range = document.createRange();
range.setStart(text, 3);
range.setEnd(container, 1);
const logRange = (expectedAncestor) => {
console.log(JSON.stringify([
range.commonAncestorContainer === expectedAncestor,
range.startOffset,
range.endOffset,
range.collapsed,
range.toString(),
]));
};
logRange(container);
range.collapse(true);
logRange(text);
}
</script>Result
[true,3,1,false,"B"] [true,3,3,true,""]
Save the example as an HTML file, open it in a browser, and check the output in the developer console. Offset `3` in the text node is just after the emoji, which uses two UTF-16 code units. Offset `1` in the element is after its only child. The range therefore contains `B`. After `collapse(true)`, both boundaries are at offset `3` in the text node, which is now the common ancestor container.
Related lessons
- JavaScript · Lesson 33 · Intermediate · Version: 3