document.evaluate with XPathResult.FIRST_ORDERED_NODE_TYPE 返

document.evaluate with XPathResult.FIRST_ORDERED_NODE_TYPE returns undefined

本文关键字:ORDERED NODE TYPE FIRST evaluate with XPathResult document      更新时间:2023-09-26

Firebug 将 xpath 结果打印为未定义,但并非未定义

function xpathTest()
{
 var div1 = document.getElementById("div1");
 var result = document.evaluate("//div[text()='Hello']", div1, null, 
                 XPathResult.FIRST_ORDERED_NODE_TYPE, null);
 console.log(result); // Firebug prints undefined
 console.log(result === undefined); // prints false
 console.log(typeof result); // prints object
 console.log(result.singleNodeValue); // prints Hello
}

在这里的网页:

<body onload="xpathTest()">
 <div id="div1">
   <div>Hello</div>
 </div>
</body>

所以xpath结果的实际toString()(?)实现是不正确的还是Firebug的错?

似乎这是一个Firebug问题。

var resultDiv = document.getElementById("resultDiv");  
add("Result: " + result); // Result: [object XPathResult]
add("(result === undefined): " + (result === undefined)); 
// (result === undefined): false
add("(typeof result): " + (typeof result)); 
// (typeof result): object
add("result.singleNodeValue: " + result.singleNodeValue); 
// result.singleNodeValue: [object HTMLDivElement]
function add(content)
{
  resultDiv.innerHTML += content + "<br>";
}

参见 JS 小提琴