To uniquely identify an element, you can create a customized XPath string. The complexity of the string determines its accuracy and portability.
For instance, a basic element-only XPath query like '//html/body/div/div/p/strong' may not be distinct enough:
'//html/body[@onclick="somereallylongjavascript" and class="nosidebar"]/div[@id="wrapper" and @class="posts"]/div[@class="entry" and @id="firstentry"]/p[@class="first"]/strong'</pre>
But focusing on specific attributes, such as IDs, can strike a good balance:
'//html/body/div[@id="wrapper"]/div[@id="firstentry"]/p/strong'
All web browsers support native retrieval of XPath. For W3C compliant method:
var myElement=document.evaluate(
XPathstring,
document,
function(ns){return{'html':'http://www.w3.org/1999/xhtml','':null}[ns];},
9,
null
).singleNodeValue;
(the ns function is mainly for application/xhtml+xml support)
Internet Explorer offers a simpler but less versatile approach:
var myElement=document.selectSingleNode(XPathString);
Creating the XPath string requires additional tools since there's no built-in solution. One option is using XPather, a Mozilla add-on with an interface for this purpose. Alternatively, shorter scripts are available for quicker solutions.
Edit: Check out Justin Johnson's link to a concise XPath-generation function on Stack Overflow. While it has some quirks like non-standard ID notation and lack of toLowerCase()
for tag names, it could suit your needs perfectly.