Differences on DOM javascript setAttribute method between IE & other browsers.

Because a project of my job, I’m working in a dinamic creation of a webpage using Javascript to handle DOM.

Today I realised, that my original code (according to W3C) does not work properly with any version of IE, so for example, originally to create a input element I did:

1
2
3
4
5
6
7
8
9
// code
INPUTELM = document.createElement('input');
INPUTELM.setAttribute('name', 'codes[]');
INPUTELM.setAttribute('type', 'text');
INPUTELM.onkeyup = function(){ChangeSelectArticleByValue(this.value,'article' + (num_linies-1))}
INPUTELM.setAttribute('class', 'boxes');
INPUTELM.setAttribute('id', 'code' + (num_linies-1));
INPUTELM.setAttribute('tabindex',tabIndex);
// more code

The class attribute was not set, neither tabindex. After searching for a while I found that I might use (new methods below each one, lines 7 and 10)

1
2
3
4
5
6
7
8
9
10
// code
INPUTELM = document.createElement('input');
INPUTELM.setAttribute('name', 'codes[]');
INPUTELM.setAttribute('type', 'text');
INPUTELM.onkeyup = function(){ChangeSelectArticleByValue(this.value,'article' + (num_linies-1))}
INPUTELM.setAttribute('class', 'boxes');
INPUTELM.className= 'boxes'; // ADDED LINE
INPUTELM.setAttribute('id', 'code' + (num_linies-1));
INPUTELM.setAttribute('tabindex',tabIndex);
INPUTELM.tabIndex = tabIndex; // ADDED LINE

So mainly it seems that we might:

  • Use setAttribute for all most browsers, and the property for IE. Each browser will execute their code and avoid the other one.
  • To set class, use className because “class” is a JS reserved word.
  • Note uppercase in two or more words attributes.

I will edit this post if I deep on this.

 

Leave a Reply

Your email address will not be published. Required fields are marked *