views:

158

answers:

1

When running on an xhtml page, xpath doesn't seem to return any results.

var result = document.evaluate( "//a/img", document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );

For example returns an empty result set. What's the problem here, and how do I fix it?

+3  A: 

xhtml elements are not in null namespace, so you have to pass a namespace resolver to the method:

function resolver(prefix) {
    return prefix === 'x' ? 'http://www.w3.org/1999/xhtml' : null;
}
var result = document.evaluate( "//x:a/x:img", document.body, resolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
Azat Razetdinov