Note: This question and its answer are valid for most/all programming languages and libraries that support XPath, not just JavaScript!
With the following code that creates a very simple HTML-page (the actual code loads a remote page, but I'm trying to put your focus on the main problem here):
var dt = document.implementation.createDocumentType("html", "-//W3C//DTD HTML 4.01 Transitional//EN", "http://www.w3.org/TR/html4/loose.dtd");
var doc = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html", dt);
var src = "<head></head><body></body>";
doc.documentElement.innerHTML = src;
alert(doc.evaluate(".", doc, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue);
alert(doc.evaluate("/body", doc, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue);
alert(doc.evaluate("//body", doc, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue);
alert(doc.evaluate("/html", doc, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue);
The first alert()
shows "[object HTMLDocument]", the other alert()
shows "null". Why is that? What am I missing to make XPath queries work and have it find the body-element?
EDIT:
- added "//body" in the example
- I guess I should mention that I use Opera 12.17. Is there any workaround that would lead me to the same result?