Access html element using xpath

Is it possible to use xpath to access an html element?

It should run in interenet explorer, and I am writing it in javascript

I am trying to get the value of a specific input field on a specific row, but I do not want iterating through all cells to get the correct

Any help would be appreciated

Emma

+7
html xpath
source share
4 answers

You can use the following to access an element with known XPATH

document.evaluate ("X_PATH_EXPRESSION", document, null, XPathResult.ANY_TYPE, null) .iterateNext ()

For example, to access an element with the identifier myID

document.evaluate ("// * [@id = 'myID']", document, null, XPathResult.ANY_TYPE, null) .iterateNext ()

I tested this with firefox 3.6

+13
source share

Unfortunately, you cannot use XPath only with Javascript and HTML, but most Javascript frameworks have a selector that gives you XPath-like functionality (like jQuery )

edit: There is a specific browser version of xpath apis that you could use, but I would not recommend using them without an abstraction.

+4
source share

In IE, xpath requests are made 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 requests in html you need a third-party library like http://dev.abiss.gr/sarissa/

Also see Various Results Selecting HTML Elements with XPath in Firefox and Internet Explorer for the Previous Related Discussion

+1
source share

If HTML is XHTML-compatible, then technically, it must have access to elements through XPath. But overall it doesn't seem to work so well. Moreover, you want to do this on the client side, with any XPath library installed on the client machine. Not very useful and probably will not work.

However, with HTML, you can specify classes and names to identify specific elements on your page, and JavaScript has many functions that can simply use these methods. See http://onlinetools.org/articles/unobtrusivejavascript/chapter2.html for a simple example. Basically, JavaScript has built-in support for the HTML DOM, but not for the XML DOM.

+1
source share

All Articles