Javascript: Element setAttribute in MSIE

Posted on June 4, 2009

0


Another frustrating thing about Microsoft product is the standard. I have developed so many web application using third party javascript library or framework, such as Yahoo! User Interface. But now, thanks to the custom javascript build that I have to do, I get a new knowledge that developing a framework/library that work in many plarforms is CERTAINLY NOT FUN.

I have been developing one application for a few days and it looks stable now, well in Firefox. And then… As you should know that Microsoft Internet Explorer (MSIE) covers a big market of web browser, click here to believe, I check my application on MSIE. And wow!!! *!@#$%^&* it’s a total mess. I can’t use anything, I can’t do anything, the display is all over the place.

Long story short, the issue is root-caused to the javascript function “setAttribute”. I find these arguments don’t work in MSIE:

  • <element>.setAttribute(‘class’,'<value>’);
  • <element>.setAttribute(‘style’,'<value>’);
  • <element>.setAttribute(‘onclick’,'<value>’);

To fix the issue:

  • the <element>.setAttribute(‘class’,'<value>’) has to be replaced with <element>.className='<value>’. Yes, it is “className”, not “class”.
  • the <element>.setAttribute(‘style’,'<value>’) is more tricky, I didn’t try for the whole thing. But I know that if you have <element>.setAttribute(‘style’,’display:none’), it has to be changed to <element>.style.display = ‘none’.
  • For the <element>.setAttribute(‘onclick’,’javascript:alert(“…”)’), you only need to modify it to <element>.onclick = function() { alert(“…”); }. Looks simple? Yes, it is because the function is simple.

Actually, the last one is the worst. Let’s assume that you dynamically append new elements, which have `onclick` attribute that contains dynamic variable `x`. As you perform loop to create the elements, the `x` value rolls. Using <element>.setAttribute(‘onclick’, ‘javascript:alert(‘+x+’)’), the value of `x` will vary from one element to the other but not for the <element>.onclick = function() { alert(x); }. Got it?

Fortunately, the value that I pass to the function is the id of the element. So, I modified my code to <element>.onclick = function() { alert(this.getAttribute(‘id’)); }. Yes, for that particular element, I did <element>.setAttribute(‘id’, ‘<value>’); to ensure that the `onclick` function can access the `id`. Interesting?

Tagged:
Posted in: MyWay, Technology