getElementsByName IE fix

I was recently writing a bit of javascript to collapse / expand sections on a page. These sections are output by a bit of PHP and I don’t know how many there are likely to be, so I gave them the same name and looped through them with getElementsByName().

Now this works fine with Firefox, but I ran into a few problems with IE. It turns out that IE doesn’t support it, but luckily someone has posted an alternative solution here which I thought was rather clever. Here it is again incase the site isn’t available later on.

function getElementsByName_iefix(tag, name) {

var elem = document.getElementsByTagName(tag);
var arr = new Array();
for(i = 0,iarr = 0; i < elem.length; i++) {
att = elem[i].getAttribute(”name”);
if(att == name) {
arr[iarr] = elem[i];
iarr++;
}
}
return arr;
}

Leave a Reply