I\'m trying to select a specific HTML element in a document, for firefox i just use:
xpathobj = document.evaluate(xpath, document, null,
XPath
jQuery implements a cross-browser-compatible subset of xPath selectors with a plug-in. Your example "/HTML/BODY/DIV[9]/DIV[2]" should work in it.
(edit - corrected thanks to Sergey Ilinsky)
Another JavaScript implementation of W3C Dom Level 3 XPath can be found on Source Forge. But does not appear to be active.
Instead of doing
xmlDoc.load(document);
try
xmlDoc.loadXML(document.body.outerHTML)
This would only really work if your your HTML document is formatted to XHTML standards. Also, the BODY tag would be the root node, so you would have to change your XPATH to "/BODY/DIV[9]/DIV[2]"
Are you sure X-Path is implemented in your version of Internet Explorer? As in: what version are you using?
There are some bugs in oly1234's code I try to fix it as follows:
function getXPathElement(xpath, element){
if(!element){
element = document;
}
var xpathArray = xpath.split("/");
element = findXPathRoot(xpathArray[0],xpathArray[1],element);
for(var i=1; i<xpathArray.length; i++){
if(xpathArray[i].toLowerCase()=="html"){
continue;
}
if(!element){
return element;
}
element = getXPathElementByIndex(element.childNodes,xpathArray[i]);
}
return element;
}
function findXPathRoot(rootPath,htmlPath,element){
if(rootPath == ""&&htmlPath.toLowerCase() == "html"){
return element.documentElement;
}
return document.getElementsByTagName(rootPath)[0];
}
function getXPathElementByIndex(decendents, xpathSegment){
//seperate the index from the element name
var temp = xpathSegment.split("[");
var elementName = temp[0];
//get the index as a number eg. "9]" to 9
if(temp[1]){
var elementIndex = temp[1].replace("]", "");
}else{
var elementIndex = 1;
}
//the number of matching elements
var count = 0;
for(var i=0;i < decendents.length; i++){
if (decendents[i].nodeName.toLowerCase() == elementName.toLowerCase()) {
count++;
if(count==elementIndex){
return decendents[i];
}
}
}
return null;
}
I'd be a bit worried about using xml like this, as you cannot be sure what version (if any) of the XML DLL a person has. There are still companies using IE5.0 out there in droves, and 5.5 had a particularly ropey XML implementation.