Reputation:
can you use xpath to access an html element?
It must run in interenet explorer, and i am writing it in javascript
I am trying to get the value of a specific input box in a specific row, but i don't want to have to iterate through all the cells to get the right one
Any help would be appreciated
Emma
Upvotes: 8
Views: 15202
Reputation: 5387
You can use the following to access an element with the known XPATH
document.evaluate("X_PATH_EXPRESSION", document, null, XPathResult.ANY_TYPE, null).iterateNext()
For example to access an element with ID myID
document.evaluate("//*[@id='myID']", document, null, XPathResult.ANY_TYPE, null).iterateNext()
I have tested this with firefox 3.6
Upvotes: 13
Reputation: 26682
If the HTML is XHTML-conformant then technically, it should be possible to access elements through XPath. But in general it doesn't seem to work that well. Especially since you want to do this client-side, with whatever XPath library that's installed on the client machine. Not very useful and likely to fail.
However, with HTML you can specify classes and names to identify certain elements in your page and JavaScript has plenty of functions that can just use these methods instead. See http://onlinetools.org/articles/unobtrusivejavascript/chapter2.html for a simple example. Basically, JavaScript has native support for the HTML DOM, but not for the XML DOM.
Upvotes: 1
Reputation: 74507
Unfortunately you cannot use XPath with just Javascript and HTML but most Javascript frameworks have selectors that give you XPath-like functionality (e.g. jQuery)
edit: There are browser specific xpath apis you could use but I would not recommend using them without abstraction.
Upvotes: 4
Reputation: 57157
In IE, xpath queries are done using:
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("books.xml");
xmlDoc.selectNodes(xpath);
See http://www.w3schools.com/XPath/xpath_examples.asp
However, this only works for xml. For xpath queries on html, you need a 3rd party library like http://dev.abiss.gr/sarissa/
Also see Different results selecting HTML elements with XPath in Firefox and Internet Explorer for a previous, related discussion
Upvotes: 1