page: http://h4z.it/View/-20100729_designtea.jpg

code to execute in console: document.evaluate("//img",document,null,9,null).singleNodeValue

or

document.evaluate("//a",document,null,9,null).singleNodeValue

or even

document.evaluate("//html",document,null,9,null).singleNodeValue

result (tested both with Chrome and Firefox): null

I thought that page overrided document.evaluate but it shows

document.evaluate

function evaluate() { [native code] }

and delete document.evaluate does not help, so what else can it be which breaks document.evaluate ?

有帮助吗?

解决方案

The page you show in your question uses an xhtml namespace and probably so do the other pages that you are seeing this happen on.

Since you are setting null for the namespace resolver argument it cannot find the elements.

MDN Using XPath

Note: XPath defines QNames without a prefix to match only elements in the null namespace. There is no way in XPath to pick up the default namespace as applied to a regular element reference (e.g., p[@id='_myid'] for xmlns='http://www.w3.org/1999/xhtml'). To match default elements in a non-null namespace, you either have to refer to a particular element using a form such as ['namespace-uri()='http://www.w3.org/1999/xhtml' and name()='p' and @id='_myid'] (this approach works well for dynamic XPath's where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace.

So if you setup a resolver than you can access the element correctly by prefixing them:

function resolver(prefix){
   return prefix === "xhtml" ? 'http://www.w3.org/1999/xhtml' : null;
}

document.evaluate("//xhtml:a",document,resolver,9,null).singleNodeValue

.evaluate doc

Creating Resolver

If you want to get a node without having to know the namespace you can use local-name() XPath function as part of the expression

document.evaluate("//*[local-name()='img']",document,null,9,null).singleNodeValue
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top