Constructor
To create a range object, we use the following constructor:
- Range(): Returns a Range object whose start and endpoints are the global Document.
Range Methods
-
Range.compareBoundaryPoints()
Compare the Range's boundary points to those of another Range.
-
Range.compareNode()
Returns a constant indicating whether the Node is in the range before, after, inside, or around it.
-
Range.comparePoint()
Returns -1, 0 or 1 depending on whether the point is inside, outside, or before the Range.
-
Range.collapse()
The Range collapsed to one of its boundary points.
-
Range.cloneContents()
Returns a DocumentFragment that duplicates a Range's nodes.
-
Range.cloneRange()
Returns a Range object with the same boundary points as the original Range.
-
Range.createContextualFragment()
This method creates a DocumentFragment from a specified code string.
-
Range.deleteContents()
This method removes a Range's contents from the Document.
-
Range.detach()
Allows you to stop using the Range to enhance your performance.
-
Range.extractContents()
This method moves the contents of a Range into a DocumentFragment from the document tree.
-
Range.getBoundingClientRect()
This is the union of all the rectangles returned by range. Returns a DOMRect object that boundaries the whole contents of the range.getClientRects().
-
Range.getClientRects()
This method returns a list of DOMRect objects containing the aggregated results of "Element.getClientRects()" for all items in the Range.
-
Range.isPointInRange()
Returns a boolean indicating whether or not the specified point is within the Range.
-
Range.insertNode()
Adds a Node at the beginning of a Range.
-
Range.intersectsNode()
If the specified node intersects the Range, this method returns a boolean value.
-
Range.selectNode()
Sets the range in which the Node and its contents will be contained.
-
Range.selectNodeContents()
Sets the Range to hold a Node's contents.
-
Range.setEnd()
This method sets the Range's end position.
-
Range.setStart()
This method sets the Range's start position.
-
Range.surroundContents()
The contents of a Range are moved to a new Node.
-
Range.toString()
The Range's text is returned when this function is called.
Implementation of Range Methods
Different methods of Javascript range can be implemented to manipulate the selection. Below is an example of the implementation of range methods.
<!--- JavaScript Range Methods Range.deleteContents(), Range.insertNode(), Range.extractContents() --->
<html>
<head>
<title>Range methods</title>
</head>
<body>
<p id="p">Example text: <i> this is italic</i> and <b> this is bold.</b></p>
<p id="result"></p>
<script>
let range = new Range();
// the methods are implemented in the prototype of the Range object
let methods = {
deleteContents() {
range.deleteContents();
document.getElementById("result").innerHTML = "deleteContents()";
},
extractContents() {
var txt = range.extractContents();
document.getElementById("result").append("extractContents():",txt);
},
insertNode() {
range.insertNode(document.createTextNode("insertedNODE"));
document.getElementById("result").innerHTML = "insertNode() called!";
},
surroundContents() {
var newnode = document.createElement("b");
try {
range.surroundContents(newNode);
} catch(e) {
document.getElementById("result").innerHTML = e;}
},
resetExample() {
p.innerHTML = `Example text: <i> this is italic</i> and <b> this is bold.</b>`;
result.innerHTML = "";
range.setStart(p.firstChild, 2);
range.setEnd(p.querySelector('b').firstChild, 3);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
};
for(let m in methods) {
document.write(`<div><button onclick="methods.${m}()">${m}</button></div>`);
}
methods.resetExample();
</script>
</body>
</html>
Output
In the above example we have implemented the deleteContents(), extractContents, insertNode(), surroundNode() methods. The output shows that the “insertNode()” method has inserted the text “insertedNODE” into the original text. Similarly, we can implement the remaining methods as well.
You can practice by yourself with the help of Online Javascript Compiler for better understanding.
Selection
A Selection object represents the user-selected text range or the caret's current position. A user can choose from left to right (in document order) or right to left (reverse of document order). The anchor indicates where the user started the selection, whereas the focus indicates where the user finished it. When you use a desktop mouse to create a selection, the anchor is where you press the mouse button, and the focus is where you let go of the mouse button.
We call the window.getSelection() function to get a Selection object for examining or manipulating it.
Properties
Various properties of JavaScript Selection are as follows:
Selection Methods
There are various built-in methods for Selection. The methods are as follows:
-
Selection.addRange()
We use this method to add an item to the selection as a Range object.
-
Selection.collapse()
This method reduces the current selection to a single point.
-
Selection.collapseToEnd()
The selection is collapsed to the end of the last range in the selection.
-
Selection.collapseToStart()
The selection is collapsed to the beginning of the first range in the selection.
-
Selection.containsNode()
Indicates whether or not a particular node is included in the selection.
-
Selection.deleteFromDocument()
The content of the selection is removed from the document.
-
Selection.extend()
This method sets the selection's emphasis to a specific location.
-
Selection.getRangeAt()
Returns a Range object that represents one of the current ranges.
-
Selection.modify()
The current selection has been changed.
-
Selection.removeRange()
A range is removed from the selection.
-
Selection.removeAllRanges()
All ranges are removed from the option.
-
Selection.selectAllChildren()
The children of the specified node are added to the selection.
-
Selection.setBaseAndExtent()
This method sets the selection to a range that includes all or parts of two DOM nodes and any content between them.
-
Selection.toString()
Returns the string that the selected object is presently representing, i.e. the currently selected text.
Implementation of Selection Methods
<!-- JavaScript Selection.removeAllRanges() and Selection.addRange() methods -->
<p id="text">Lorem <i>ipsum</i> dolor <i>amet</i> consectetur <i>adipiscing elit</i></p>
From <input id="start" type="number" value=1> to <input id="end" type="number" value=4>
<button id="btn">Select</button>
<script>
btn.onclick = () => {
// define range
let range = new Range();
// set start and end
range.setStart(text, start.value);
range.setEnd(text, end.value);
// select range
document.getSelection().removeAllRanges();
document.getSelection().addRange(range);
};
</script>
Output
Here, the text “Lorem” gets the offset 0, and “ipsum” gets 1. So the selection ranges from “ipsum” to “amet.” We have implemented the methods “Selection.removeAllRanges()” and “Selection.addRange().”
Selection Events
There are events taking place to keep track of the selection process:
- elem.onselectstart: When a selection begins on an element only (or inside it). For example, when the user hits the mouse button, the cursor begins to move. The start of the selection is cancelled if the default action is disabled. As a result, beginning a selection from this element is no longer feasible, but the element remains selectable. The visitor only needs to begin the choosing process from somewhere else.
- document.onselectionchange: When a selection changes or starts, "document.onselectionchange" is called. Please note that this handler can only be configured on a document, and it will track all selections made within it.
Frequently Asked Questions
What is a JavaScript range object?
The start and endpoints of a Range object define it. An element and its position define a point. The position specifies a character position within the element if the element solely includes text content (TextNode, CDATASection, or CommentNode), otherwise, it specifies the index of a child of the element.
In a coding interview, is JavaScript important?
Interviewers are evaluating you on your coding and problem-solving abilities. As a result, they will urge you to choose the programming language you are most familiar with and fluent in. If you know and can code in JavaScript, it's the most significant language to utilise in an interview.
In JavaScript, what does an object mean?
An object is a separate entity having properties and a type in JavaScript. As an example, consider a cup. A cup is a property-based object. A cup has a colour, a pattern, a weight, and a material. JavaScript objects can have properties that specify their qualities in the same way.
Is JavaScript synchronised or asynchronous?
JavaScript is a highly flexible single-threaded, non-blocking, asynchronous, concurrent programming language. Wait a minute, did that say single-threaded and asynchronous all at once? If you're familiar with the term "single-threaded," you probably think of synchronous operations.
Conclusion
This article extensively discussed JavaScript Selection and Range and various properties and methods associated with them. We illustrated these two concepts by implementing them in HTML. The basic concepts of JavaScript Selection and Range will help you manipulate text selections in web programming.
We hope that this blog has helped you enhance your JavaScript Selection and Range knowledge. If you want to learn more, check out our articles on "Javascript BOM," "Event Loop in JavaScript," "Regular Expressions in JavaScript," and "JavaScript DOM." Do upvote our blog to help other ninjas grow.
Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations and much more!
Happy Reading!