XML DOM compareDocumentPosition() 方法
定义和用法
compareDocumentPosition() 方法可以根据文档顺序使用指定的节点比较当前节点的文档位置。
语法:
nodeObject.compareDocumentPostition(node)
Parameter | Description |
---|---|
node | Required. Specifies the node to be compared with the current node. |
Example
In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
The following code snippet can compare the document position of the first book element and the third book element:
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book')[0];
var y=xmlDoc.getElementsByTagName('book')[2];
document.write(x.compareDocumentPosition(y)
);
Output:
4
Note:Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the above example, Mozilla browser will output 4, while Internet Explorer will output 2.
Tip:For more information about the differences between XML DOM in IE and Mozilla browsers, please visit our DOM browser Chapter.