outerHTML
outerHTML
is a good choice with several limitations:
- today (2014) you can't get attached listeners natively
- outerHTML uses html node serialization, which uses uses xml attributes serialization algorithm
In other words, IDL attributes are ignored, only content attributes are serialized.
Events by IDL attributes are coded as
div.onmouseover=function(){div.style.color = "red"};
div.addEventListener("mouseover",function() {div.style.backgroundColor="blue";});
See more about events
Whereas events by content attributes are coded as
div.setAttribute("onmouseover","this.style.color='red'");
Using content attribute, the outerHTML looks like this:
<div onmouseover="this.style.color='red'" style="border: 1px dotted red;">
I'm the div
</div>
See your updated fiddle.
Long story short, there are two ways to code a handler:
var setColor = function(e) { e.target.style.color = "red"; }
div.onmouseover = setColor; // IDL, not seen by outerHTML
div.setAttribute("onmouseover","setColor(event)"); // content, seen by outerHTML
eventListenerList
If you want to retrieve the IDL events somehow, nice proposed eventListenerList
property was removed from DOM3 spec proposal (see here).
If you want to write a firefox addon (something like code inspector), extending the Element.prototype will do the trick (as I tested, it works in Firefox, Chrome and Opera, it doesn't work in IE7):
(function() {
Element.prototype.eventListenerList = {};
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
this._addEventListener(a,b,c);
if(!this.eventListenerList[a]) this.eventListenerList[a] = [];
this.eventListenerList[a].push(b);
};
})();
To be precise, you should also override the Element.prototype.removeEventListener
to remove the event from the custom EventListenerList.
Now you can add the events by addEventListener
as usual:
function handlerA() { alert('a'); }
function handlerB() { alert('b'); }
function handlerC() { alert('c'); }
// attach handlers
div.onclick = handlerC;
div.addEventListener("click",handlerA);
div.addEventListener("click",handlerB);
...and to display the code of the listeners. I will do this for onclick
event, in your code you should iterate through every possible event. Don't forget the eventual onclick
listener (you can't override Element.prototype.onclick
because it is non-configurable property):
var clickListeners = "";
if(div.eventListenerList.click)
div.eventListenerList.click.forEach(function(f) {
clickListeners+= f.toString();
});
if(div.onclick) clickListeners+= div.onclick.toString();
alert(clickListeners);
See and test the fiddle. Put these pieces together as it suits to your addon.