Home > Article > Web Front-end > Complete set of Javascript standard DOM Range operations_Basic knowledge
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
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
)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
The cloneContents() method can clone the fragment of the selected Range, for example:
Hello World
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
Then the original HTML will become like this:
HeInserted textllo World
Hello World
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
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
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
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;
}
};
}