Saturday, June 2, 2007

IE DOM Issue

Recently I had an issue wherein I had to create new HTML element via DOM.And these HTML elements needed to have some properties as well HTML events like onClick(), onMouseOver(), etc.

While doing so my code worked perfectly fine in FireFox, but in IE the new elements created did not behaved in desired manner.
After a bit research I found that setAttribute() function doesnt work always in IE (actually it is suppose to not work at all ;)..).

Substitue for using setAttribute() is to use innerHTML
eg.TR1.innerHTML = "";

In my case innerHTML didnt worked as i had too many parameters to pass wherein I was out of combinations for using single and double quotes.

Below were the different ways I tried.
Not one of the following examples worked in IE:

TD1.setAttribute('onclick', 'doThis(' + param + ');');
TD1.onclick = 'doThis(' + param + ');';
TD1.onclick = new Function('doThis(' + param + ');');
TD1.onclick = function() { doThis(param); };
TD1['onclick'] = 'doThis(' + param + ');';
TD1['onclick'] = new Function('doThis(' + param + ');');
TD1['onclick'] = function() { doThis(param); };

The hack for making onClick work for you in IE via DOM

TD1.onclick = function() {
var temp = new Function("dostuff('"+myvar+"')");

The above code works well with both IE and Mozilla.
The same technique is to be used for calling any function for any HTML Events(onMouseOver).

NOTE: The above code can be simplified only when the function you are calling (dostuff) does not have any parameters to pass.

TD1.onclick = function() { dostuff(); }

Some more interesting hacks for making your DOM work in IE are


blah.className = 'myCSS'; <-- This line needs to be added

blah.setAttribute('valign', 'top'); This wont work as IE is case-sensitive
blah.setAttribute('vAlign', 'top');

Reference: Why IE Sucks


Chrelad said...

I just had the same problem... IE SUCKS! :P Thanks for posting the resolution to the problem. I'll put this on if you don't mind so that others can benefit from this resolution!

Thanks again Vinay,


Vinay Nihalani said...

Yeah! you can put this on As long as knowledge is being shared I dont have any issues. :)