Using and html element's addEventListener
has several advantages over using inline events, like onclick
.
However, to store the element including its inline event is straight forward, for example, by embedding it in a parent element and storing the parent's innerHTML
.
Is it possible to do something similar when using event listeners?
Edit:
I realized that my question is not sufficiently explained. So here some additions.
By "store" I mean a way to get the information holding the element and the event listener.
The analogue with inline events is easy: just embed in a parent element and save the parent's innerHTML
(string) somewhere, for example in a database, and recreate the element later by loading the string and applying it to the innerHTML of some element.
But how would one do the analogue with elements when using event listeners? One cannot just use the innerHTML
since then the events are not stored.
I hope this clarifies my question a bit.
Edit 2
With the help of comments I have made some unsuccessful attempts.
It is possible to get store the information of an element
using createDocumentFragment()
or element.cloneNode(true)
.
However, the first method does not work for external storage since, if I understood correctly, will contain only a pointer. Here is an example:
https://jsfiddle.net/hcpfv5Lu/
The second method does not work either. I am not fully sure why, but if I JSON.stringify
the clone it "vanishes". Here is an example:
innerHTML
(string) of one element and reapply it later to some other element in order to have the former element restored. – DanielDocument.createElement()
doc and attach event listeners to the created object. Then you can insert this object into a "parent" byparent.appendChild(obj)
doc. Then you can "store" the objects in JavaScript. – E. Sundin