Ali Ali - 4 months ago 11x
CSS Question

IE not allowing onClick event on dynamically created DOM 'a' element

I'm having issues with internet Explorer. I have a link which duplicates a file upload element on a form. The code which duplicates also appends a hyperlink to the duplicated upload element which is supposed to remove the duplicated element a simple remove this link.

The issue is that this code runs fine in firefox but it doesn't run at all in IE. Forget how the code is written out - the onClick event which I attach to the element doesn't fire at all!

I'm creating my remove link element like this in the function:

var a = document.createElement('a');
a.setAttribute('href', "javascript:void(0);");
a.setAttribute('class', 'delete');
a.setAttribute('onClick', 'removeThisElement(idOfParentContainer, this)');


This works fine in firefox but it doesn't fire at all in IE. I checked the dom using IE inspector and the link has rendered nicely however the class attached to it hasn't rendered or been applied and neither has the event fired even though it has physically been appended to the link on the html. For some reason the onClick event is not even firing no matter what code I put in it even if its an alert. Am I missing something here. :(

Great got part one of the issue solved by attaching events using AddEvent however why isn't the css rendering I mean the class attached to the element doesn't render at all for some weird reason :(

Good advice indeed - I'm rewriting my code to avoid the setAttribute function and instead porting all this DOM manipulation to jquery. Thanks for the helps guys


Event handlers are not DOM attributes, the attribute exists in markup only - I'm not sure why FF oks this. I'll go research that now cause I want to know.

Update: seems to be mixed feelings about whether eventhandlers are DOM-valid attributes or not. Looks to me like this is MS's fault as they internally do not treat them as attributes, whilst the HTML spec indicates that they very much are. The direct consequences of this are that a number of things !IE would consider attributes cannot be set with setAttribute in IE including eventhandler bindings and importantly also style, class and name. apparently IE8 fixes this but I still haven't installed that so I can't check.

Meanwhile, for event binding use the addEventListener/attachEvent pair instead, or (less preferably because it's a direct assignment) set a.onclick directly to your target method (or more likely a closure on your method).

To fix your styling not being correctly applied use = foo; or (better) element.className = bar.

Essentially the problem is setAttribute. Avoid using it.

For reference...