XML DOM compareDocumentPosition()メソッド
❮ノードオブジェクト
例
次のコードフラグメントは、「books.xml」をxmlDocにロードし、DOM階層内の2つのノード(最初と3番目の<book>要素)の配置を比較します。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x =
xmlDoc.getElementsByTagName('book')[0];
var y =
xmlDoc.getElementsByTagName('book')[2];
document.getElementById("demo").innerHTML =
x.compareDocumentPosition(y);
}
上記のコードの出力は次のようになります。
4
ほとんどのブラウザは、空の空白または新しい行をテキストノードとして扱いますが、IE9以前は扱いません。したがって、上記の例では、ほとんどのブラウザーは4を出力しますが、IE9以前は2を出力します。
定義と使用法
compareDocumentPosition()メソッドは、DOM階層(ドキュメント)内の2つのノードの配置を比較します。
ブラウザのサポート
compareDocumentPosition()メソッドは、すべての主要なブラウザーでサポートされています。
注: Internet Explorer 9以前は、この方法をサポートしていません。
構文
nodeObject.compareDocumentPosition(node)
パラメーター
Parameter | Type | Description |
---|---|---|
node | Node object | Required. Specifies the node to compare with the current node |
戻り値
Type | Description |
---|---|
Number | A Number representing where the two nodes are positioned compared to each other. The possible return values
are:
1 - No relationship, the two nodes do not belong to the same document. 2 - The specified node precedes the current node. 4 - The specified node follows the current node. 8 - The specified node contains the current node. 16 - The specified node is contained by the current node. 32 - The specified and the current node have no common container node or the two nodes are different attributes of the same node. Note: The return value could also be a combination of values. E.g. a return value of 20 means that the specified node is contained by the current node (16) AND the specified node follows the current node (4). |
技術的な詳細
DOMバージョン | コアレベル3ノードオブジェクト |
---|
❮ノードオブジェクト