I am trying to add an event handler on a page through javascript. What I tried is as follows,
var span=document.getElementById("WD67");
span.setAttribute("onchange","alert('hello');");
But though the event handler attribute gets added, it doesn’t fire when the page is viewed in IE, however in Firefox it works properly. How do I get IE to recognize it?
Don’t use attributes for that. The best way to add event handlers is using
addEventListener(all modern browsers) orattachEvent(IE<9). Furthermore, use a handler function reference (wrapalert('hello')in a function).A crossbrowser function to add handlers to elements:
See also: this jsfiddle