tags:

views:

770

answers:

4

Hi,

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

+1  A: 

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.

Josef
A: 

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 http://stackoverflow.com/questions/178016/problem-selecting-html-elements-with-xpath-in-internet-explorer for a previous, related discussion

Jonathan Fingland
whenerv i try and use xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0");i get an accessed denied message although i have lifted all the security i canany ideas?
A: 

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.

Workshop Alex
A: 

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 firefox 3.6

Kalinga