access html element using xpath

14,888

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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.

Share:
14,888
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin about 2 years

    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

  • Admin
    Admin about 15 years
    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?
  • Raja
    Raja almost 13 years
    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 mcc.id.au/xpathjs