


Level 2 DOM defines a createRange() method, if it is a browser that follows the DOM standard (IE does not support this standard, but there are many more attributes or methods in IE than those defined in the standard) , it belongs to the document object, so to create a range object do this:
var oRange = document.createRange();
If you want to detect whether your browser supports this standard Range object , can be detected using the hasFeature() method:
var supportsDOMRanges = document.implementation.hasFeature("Range", "2.0");
if (supportsDOMRange) {
var oRange = document. createRange();
//range code here
}
Range object for simple selection
It is easiest to use Range to select, use the selectNode() or selectNodeContents() method , these two methods have only one receiving parameter, a DOM node.
The selectNode() method selects all nodes, including its children, while selectNodeContents() selects only its children. Such as
Hello World
<script><br/>var oRange1 = document.createRange(); <br/>var oRange2 = document.createRange();<br/>var oP1 = document.getElementById("p1");<br/>oRange1.selectNode(oP1);<br/>oRange2.selectNodeContents(oP1);<br/> </script>
oRange1 and oRange2 include the two methods mentioned above, but after looking at the diagram below, I believe you can quickly understand the difference between these two methods:
When you create a Range object, the Range instance will have the following properties:
startContainer — Returns the node object where the range object starts ( The first node of the parent node)
startOffset — Returns the offset (offset) of the start of the Range. If startContainer is a text node, annotation node, or a CDATA node, this property returns the offset of the text, otherwise it returns The index of the first node.
endCOntainer — Returns the last node object of the Range object (the last node of the parent node)
endOffset — Returns the offset (offset) at the end of the Range. The characteristics are the same as startOffset.
commonAncestorContainer — Returns the first node containing the Range object.
Note: These attributes are read-only. startOffset and endOffset will be explained in more detail below.
The following code will illustrate these properties, please run it in Mozilla firefox (browsers that support this standard - DOM2 level, will not work in IE):
Hello World
|
|
The above code will not be commented. If you have any questions, please leave them in the comments.
There are some other methods in Range:
setStartBefore(node) — Set the starting position of the Range relative to the node node
setStartAfter(node) — Same as above
setEndBefore — Set the Range The end position relative to the node node
setEndAfter — Same as above
Complex DOM Range
To build a complex DOM range, you need to use setStart() and setEnd() Two methods, these two methods have two parameters: one is a node reference and an offset. In the
setStart method, the node reference is startContainer, and the offset is startOffset; in the
setEnd() method, the node reference is endContainer, and the offset is endOffset.
Using these two methods is similar to the selectNode() and selectNodeContents() methods. For example, in the previous example of the useRanges() function below, you can use setStart() and setEnd():
function useRanges() {
var oRange1 = document.createRange();
var oRange2 = document.createRange();
var oP1 = document.getElementById("p1");
var iP1Index = -1;
for (var i=0; i if (oP1.parentNode.childNodes[i] == oP1) {
iP1Index = i;
break;
}
}
oRange1.setStart(oP1.parentNode, iP1Index);
oRange1.setEnd(oP1.parentNode, iP1Index 1);
oRange2.setStart(oP1, 0);
oRange2.setEnd(oP1, oP1.childNodes.length);
//textbox assignments here
}
Note that when selecting a node (oRange1), you must specify all the nodes in the oP1 parent node An index into the childNodes collection.
The code for selecting content (oRange2) does not require additional consideration.
From the example just now, from this HTML (code
Hello World
)Select the Range starting from llo in hello to starting from Wo in World, we use setStart() and setEnd(), it is easy Do it.
First, we must use regular DOM methods to get the reference to the text node and the reference to the container p1.
var oP1 = document.getElementById("p1");
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
Description :
The text Hello is actually the grandson node of container p1, so we can use oP1.firstChild to get the element. oP1.firstChild.firstChild is the reference of the Hello text node, and World is the reference of container p1. The last node.
Next step, create the range and set the offset:
var oP1 = document.getElementById("p1");
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
Explanation:
For setStart(), the offset (offset) is 2, because the position of the letter l in the text node (that is, Hello) is 2, (the position is calculated from 0), set setEnd( ) The offset in the method is 3 for the same reason as above. It should be noted that there is a space in front of World, and the space also takes up space. As shown in the picture:
Note:
(Mozilla DOM Range bug #135928) Execute this Range method in a lower version of Mozilla browser When setStart() and setEnd() both point to the same text node, an exception will occur
Use DOM Range to do some operations
When creating a Range object, in Range On top of all the objects, a fragment node of the document has been created. Before that, the Range object must be qualified to prove that the Range you selected is well-formed.
For example, take the Range
Obviously, here, it is not well-formed. As mentioned above, when When creating a Range, a fragment will be automatically generated. Here, the fragment will automatically and dynamically add some elements to ensure the correctness of the Range:
Hello World
means that the start tag is automatically added, making the entire Range become llo Wo, diagram of fragment For:
After this fragment is created, you can use some methods of Range to operate it.
The simplest operation is: deleteContents() method. This method will delete the selected part of Range. After the above operation, deleteContents() is performed. Then the remaining HTML will be:
Herld
The reason why the closing tag is added is as mentioned above, and Range is to ensure that it is well-formed .
The extractContents() method is similar to deleteContents(), but the specific operations are different. extractContents() moves the selected Range from the DOM tree to a fragment and returns this fragment. Copy the following code and then Run it in Mozilla Firefox and you will understand after looking at the results. ——The deleted llo Wo is added to the end of the body as a fragment.
Hello World
<script><br/>var oP1 = document.getElementById("p1" );<br/>var oHello = oP1.firstChild.firstChild;<br/>var oWorld = oP1.lastChild;<br/>var oRange = document.createRange();<br/>oRange.setStart(oHello, 2);<br/>oRange.setEnd(oWorld, 3);<br/>var oFragment = oRange.extractContents();<br/>document.body.appendChild(oFragment);<br/></script>
The cloneContents() method can clone the fragment of the selected Range, for example:
Hello World
<script></script>var oP1 = document.getElementById("p1");
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
var oFragment = oRange.cloneContents();
document.body.appendChild(oFragment);
This method is similar to extractContents(), but it is not deleted, but cloned.
Insert some data from Range
The methods in the previous section solve how to remove the selected fragment in the range. Now explain how to add content to the Range.
The insertNode() method can insert a node into the Range. What if I want to insert the following nodes into Range?
Inserted text
Look at the code below:
Hello World
<script><br/>var oP1 = document.getElementById("p1");<br/>var oHello = oP1.firstChild.firstChild;<br/>var oWorld = oP1.lastChild;<br/>var oRange = document.createRange();<br/>var oSpan = document.createElement("span");<br/>oSpan.style.color = "red";<br/>oSpan .appendChild(document.createTextNode("Inserted text"));<br/><br/>oRange.setStart(oHello, 2);<br/>oRange.setEnd(oWorld, 3);<br/>oRange.insertNode(oSpan) ;<br/></script>
Then the original HTML will become like this:
HeInserted textllo World
surroundContents()'s parameter is a node, which will add this node to the Range. See this example below .
Hello World
<script><br/>var oP1 = document.getElementById("p1" );<br/>var oHello = oP1.firstChild.firstChild;<br/>var oWorld = oP1.lastChild;<br/>var oRange = document.createRange();<br/>var oSpan = document.createElement("span") ;<br/>oSpan.style.backgroundColor = "yellow";<br/><br/>oRange.setStart(oHello, 2);<br/>oRange.setEnd(oWorld, 3);<br/>oRange.surroundContents(oSpan) ;<br/></script>
There is a newly generated node span within the range selected by oRange, so the background of the selected Range turns yellow.
collapse() method: The
collapse() method has only one Boolean parameter, which is optional, that is, it can be present or not, and the default is false.
When true, it folds to the beginning of the Range boundary; when it is false, it folds to the end of the Range. That is
Hello World
<script><br/>var oP1 = document.getElementById("p1");<br/>var oHello = oP1.firstChild.firstChild;<br/>var oWorld = oP1.lastChild;<br/>var oRange = document.createRange();<br/>oRange.setStart(oHello, 2);<br/>oRange. setEnd(oWorld, 3);<br/>oRange.collapse(true); <br/></script>
If you want to know whether the Range has been collapsed, you can use the collapsed attribute to get it true or false. See the example below.
Paragraph 1
Paragraph 2
<script><br/>var oP1 = document.getElementById("p1");<br/>var oP2 = document.getElementById("p2");<br/>var oRange = document.createRange();<br/>oRange.setStartAfter(oP1);<br/> oRange.setStartBefore(oP2);<br/>alert(oRange.collapsed); //outputs "true"<br/></script>
The above code outputs true. Although we did not use the collapse method, because our Range setting starts from the end of 1 to the beginning of p2, there are no elements. That is,
(Range starts)(Range ends), so the displayed value is true.
Comparison of Range boundaries
compareBoundaryPoints() method, the syntax is as follows:
compare = comparerange.compareBoundaryPoints(how, sourceRange)
Parameter meaning:
compare - returns 1, 0, -1. (0 means equal, 1 means comparerange is after sourceRange, -1 means comparerange is before sourceRange)
how - is Range constant: END_TO_END |END_TO_START|START_TO_END|START_TO_START
sourceRange - the bounds of a Range object.
Look at the example below:
Hello World
<script><br/>var oRange1 = document.createRange();<br/>var oRange2 = document.createRange();<br/>var oP1 = document.getElementById("p1");<br/>oRange1.selectNodeContents(oP1);<br/> oRange2.selectNodeContents(oP1);<br/>oRange2.setEndBefore(oP1.lastChild);<br/>alert(oRange1.compareBoundaryPoints(Range.START_TO_START, oRange2)); <br/>//outputs 0<br/>alert(oRange1. compareBoundaryPoints(Range.END_TO_END, oRange2)); <br/>//outputs 1;<br/></script>
The following picture is a schematic diagram of these two Ranges. Combining the code and the above description, you can The results are clearly analyzed.
Clone Range
This operation is very simple and only requires one statement That's it:
var oNewRange = oRange.cloneRange();
cloneRange() method will return a copy of the current Range, which is, of course, also a Range object.
Clear the system resources occupied by Range
When you create a Range object, it is best to use the detach() method to clear the system resources occupied by it. Although it is not cleared, the GC (garbage collector) will also collect it, but it is a good habit to use detach() to release it. The syntax is:
oRange.detach();
The following example is in Mozilla, using Range to simulate the element.insertAdjacentHTML() method in IE,
if (browser.isMozilla) {
HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) {
var df; var r = this.ownerDocument.createRange();
switch ( String(sWhere).toLowerCase()) {
case "beforebegin":
r.setStartBefore(this);
df = r.createContextualFragment(sHTML);
this.parentNode.insertBefore(df , this);
break;
case "afterbegin":
r.selectNodeContents(this);
r.collapse(true);
df = r.createContextualFragment(sHTML);
this.insertBefore(df, this.firstChild);
break;
case "beforeend":
r.selectNodeContents(this);
r.collapse(false);
df = r.createContextualFragment(sHTML);
this.appendChild(df);
break;
case "afterend":
r.setStartAfter(this);
df = r.createContextualFragment( sHTML);
this.parentNode.insertBefore(df, this.nextSibling);
break;
}
};
}

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
