1
votes

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:

https://jsfiddle.net/3af001tq/

2
What do you mean by "store"?KevBot
@KevBot I mean a way to get the information to put it somewhere else and load it again later. For example, one could store the innerHTML (string) of one element and reapply it later to some other element in order to have the former element restored.Daniel
am i missing something? addEventListener is javascript, not htmlCruiser
You can create elements using Document.createElement()doc and attach event listeners to the created object. Then you can insert this object into a "parent" by parent.appendChild(obj)doc. Then you can "store" the objects in JavaScript.E. Sundin
http://stackoverflow.com/a/6348597/3877877 ... perhaps i misunderstood, but you can do it the same way.Martin E

2 Answers

0
votes

You could use a document fragment to store the DOM node in a JavaScript variable which can then be appended to a DOM element when required.

https://developer.mozilla.org/en/docs/Web/API/Document/createDocumentFragment

-2
votes

Yes.

You can use something like.

<ul>
   <li id="list">Some data</li>
   <li>Dumy</li>
</ul>

then in your javascript file,

document.getElementById("list").addEventListener("click", function(){
     var htmlMarkUp = this.parentNode.innerHTML;
});

This would store the html content of ul in var htmlMarkUp.