7

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

4 Answers4

13

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

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Ashok Koyi
  • 5,327
  • 8
  • 41
  • 50
  • 1
    This is the W3C way to do it. The code to create a query and traverse the results is quite long-winded, so most developers use a wrapper for it. If your browser doesn't have XPathResult, XPathParser or document.evaluate(), you can use a pure JS implementation such as http://mcc.id.au/xpathjs – joeytwiddle Jul 18 '11 at 22:28
4

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 Pfleger
  • 74,165
  • 16
  • 97
  • 99
1

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

Community
  • 1
  • 1
Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
  • 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 can any ideas? –  Jun 22 '09 at 12:35
1

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.

Wim ten Brink
  • 25,901
  • 20
  • 83
  • 149