Wednesday, January 02, 2008

for...in loop and nodeList in Safari

Several years ago, I figured out that for...in loop doesn't work with a nodeList we got from dom functions like getElementsByTagName.

Or that means

var divs = document.getElementsByTagName("div"); var i; for( i in divs ){ divs.items(i).innerHTML = "B"; }

doesn't work in Safari. Some people may know that there is another way to access a nodeList in Firefox and IE, like

var divs = document.getElementsByTagName("div"); var i; for( i in divs ){ divs[i].innerHTML = "B"; }

However, this doesn't work in Safari too. (Actually it is wrong even in Firefox and IE.) The right way is

var divs = document.getElementsByTagName("div"); var i; for( i= 0; i < divs.length; i ++ ){ divs.items(i).innerHTML = "B"; }

The reason is that in Firefox or IE, nodeList is treated as an array, but Safari doesn't.

Labels: , , ,

0 Comments:

Post a Comment

<< Home