Different results selecting HTML elements with XPa

2019-02-22 07:07发布

I'm trying to select a specific HTML element in a document, for firefox i just use:

xpathobj = document.evaluate(xpath, document, null,
               XPathResult.FIRST_ORDERED_NODE_TYPE, null);

which works fine. However when I try the IE equivilent:

xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(document);
xmlDoc.setProperty("SelectionLanguage", "XPath");
xpathobj = xmlDoc.selectNodes(xpath);

I get no object returned. So my question is there an easy way to use XPath to get to the element I want in IE? The XPath I'm using looks like

/HTML/BODY/DIV[9]/DIV[2]

10条回答
放荡不羁爱自由
2楼-- · 2019-02-22 07:41

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)

查看更多
Root(大扎)
3楼-- · 2019-02-22 07:42

The problem may be that in IE5+ [1] is in fact [2] in FF. Microsoft solely decided that the numbering should start at [0] and not [1] as specified by w3c.

查看更多
爷的心禁止访问
4楼-- · 2019-02-22 07:47

Another JavaScript implementation of W3C Dom Level 3 XPath can be found on Source Forge. But does not appear to be active.

查看更多
女痞
5楼-- · 2019-02-22 07:48

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.

查看更多
登录 后发表回答