XML DOM compareDocumentPosition() 方法
定义和用法
compareDocumentPosition()
方法根据文档顺序将当前节点的文档位置与指定节点进行比较。
语法
elementNode.compareDocumentPostition(node)
参数 | 描述 |
---|---|
node | 必需。规定与当前节点进行比较的节点。 |
实例
下面的代码将 "books.xml" 加载到 xmlDoc 中,并比较 DOM 层次结构中两个节点(第一个和第三个 <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); }
A maioria dos navegadores considera espaços em branco ou novas linhas como nós de texto, enquanto os navegadores IE 9 e anteriores não. Portanto, no exemplo acima, a maioria dos navegadores retornará 4, enquanto os navegadores IE 9 e anteriores retornarão 2.
Para obter mais informações sobre as diferenças entre navegadores, visite a seção Navegadores do tutorial XML DOM.