I’m trying to store a reference of an HTML tag for later reuse.
e.g. If I click on a div and save a pointer to that div within Javascript, will there be a way I could serialize such pointer? So I could de-serialize it and use the pointer in another instance of the web application?
Only methods I can think of are the following:
-
Use id or name attributes
-
Create a CSS selector for that element
Any other ideas guys? =)
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:
Factoring in all attributes might be overkill
But you could probably find a nice middle-ground by limiting to certain attributes, maybe just to IDs:
You can retrieve XPath natively in all browsers. There's the W3C method:
(the ns function is purely if you need application/xhtml+xml support)
The IE method is more simplistic but less flexible:
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'ttoLowerCase()itstagNames which could impair portability, but other than that it looks perfect for your needs.