JavaScript document.createRange() Method

You are Here:

JavaScript document.createRange() Method

The document.createRange() method returns a new Range object.

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

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point">Click the button to remove this content.</p> <button onclick="myFunction()">Remove content</button> <script> var x = document.getElementById("point"); function myFunction(){ var range = document.createRange(); range.selectNodeContents(x); range.deleteContents(); } </script> </body> </html>

Syntax

document.createRange()

Return Values

ValueExplanation
ObjectReturns a new Range object.

Deleting First Character

In the following example, we will delete the first character in the paragraph whenever the button is clicked.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point">Delete the first character from this paragraph.</p> <button onclick="myFunction()">Click Me</button> <script> var x = document.getElementById("point"); function myFunction() { var textNode = x.firstChild; if(textNode.data.length > 1) { var range = document.createRange(); range.setStart (textNode, 0); range.setEnd (textNode, 1); range.deleteContents(); } } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author