You could try generating an XPath string for the element - the more complex the string, the more accurate and portable an identifier it will be.
For example, a simple element-only XPath query string would not be very unique, and likely to re-occur:
'//html/body/div/div/p/strong'
Factoring in all attributes might be overkill
'//html/body[@onclick="somereallylongjavascript" and class="nosidebar"]/div[@id="wrapper" and @class="posts"]/div[@class="entry" and @id="firstentry"]/p[@class="first"]/strong'
But you could probably find a nice middle-ground by limiting to certain attributes, maybe just to IDs:
'//html/body/div[@id="wrapper"]/div[@id="firstentry"]/p/strong'
You can retrieve XPath natively in all browsers. There's the W3C 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 purely if you need application/xhtml+xml support)
The IE method is more simplistic but less flexible:
var myElement=document.selectSingleNode(XPathString);
Creating the XPath string is a different issue of course - there are various options, none native unfortunately. XPather is a moz add-on that provides an interface that does this - its source is MPL-ed and relatively simple but is probably more than you need. There are various shorter scripts available that provide simpler solutions.
Edit: Justin Johnson has provided a link to an SO answer containing a VERY short XPath-generating function. It's a bit simplistic, it uses odd id notation (id(blah)
instead of [@id="blah"]
) and doesn't toLowerCase()
its tagName
s which could impair portability, but other than that it looks perfect for your needs.