Skip to main content

Selection and Range

Miscellaneous: Selection and Range

Can you describe the fundamentals of selection in JavaScript?

View Answer:
Interview Response: JavaScript may access a current selection, select and deselect DOM nodes whole or partially, delete the selected content from the document, and encapsulate it in a tag. Range is the primary selection idea, and it is just a pair of "border points": range start and range end.

Can you please explain the function and syntax of the Range Object/interface?

View Answer:
Interview Response: The Range interface represents a document fragment that can contain nodes and parts of text nodes. The `Range()` constructor returns a newly created Range object whose start and the end are the global Document object. A Range object gets created without parameters in its initial state. Then we can set the selection boundaries using `range.setStart(node, offset)` and `range.setEnd(node, offset)`. Surprisingly, the first parameter node in both systems can be either a text node or an element node, and the meaning of the second argument is dependent on this.

Code Example:

Syntax: let range = new Range();

<p id="p">Hello</p>
let range = new Range();
range.setStart(p.firstChild, 2);
range.setEnd(p.firstChild, 4);

// toString of a range returns its content as text
console.log(range); // ll

Explain the function and syntax of the Window.getSelection() method?

View Answer:
Interview Response: The `window.getSelection()` method returns a Selection object representing the range of text selected by the user or the caret's current position. The document selection is represented as a Selection object, which may be accessed by `window.getSelection()` or `document.getSelection()`. A selection may contain 0 or more ranges.

Code Example:

Syntax: let range = new Range()let selection = window.getSelection();

<p id="p">Select me: <i>italic</i> and <b>bold</b></p>

From <input id="from" disabled /> – To <input id="to" disabled />
document.onselectionchange = function () {
let selection = document.getSelection();

let { anchorNode, anchorOffset, focusNode, focusOffset } = selection;

// anchorNode and focusNode are text nodes usually
from.value = `${anchorNode?.data}, offset ${anchorOffset}`;
to.value = `${focusNode?.data}, offset ${focusOffset}`;