Friday 15 August 2008

Useful JS script to get around IE's inability to do getElementsByName properly

If you need to use the JS function getElementsName() which works perfectly in all other browsers except that f**king slough of programming despond that is IE. Try this.

It basically overrides the getElementsById() function with a new one that unlike the spew in IE, works!

if ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) )
{
document.getElementsByName=function(str)
{
str=new String(str);
var myMatches=new Array();
var allEls=document.getElementsByTagName("*"),l=allEls.length;
for(var i=0;i<l;i++)if(allEls[i].name==str || allEls[i].getAttribute("name")==str)myMatches[myMatches.length]=allEls[i];
return myMatches;
}
}


2 comments:

Tim Tripcony said...

One nitpicky suggestion: instead of doing user agent testing, I'd recommend doing capability testing:

if (!document.getElementsByName)
{
document.getElementsByName=function(str)
{...

Couple advantages to this:
1. You're covering all browsers - if the browser has a native implementation of the function, your script uses that, otherwise it loads the custom definition. With user agent testing, a browser that doesn't have a native function but wasn't included in the regex test will fail because it thinks it doesn't need to load the custom definition.
2. For the same reason, capability testing is more forward compatible - at some point, IE or Opera will probably add native getElementsByName support; if you're doing capability testing, then as soon as a user upgrades to a version that has native support, it no longer loads the custom definition, whereas with user agent testing, the script will still assume that just because they're using IE, a custom method is needed.
3. Similarly, if you're using (or start using) a JavaScript framework, it might already have a definition for that method, or it might not... in which case future versions of the framework might add it. Capability testing, again, ensures that your script only has to define the custom method if it hasn't already been defined by something else.

Unknown said...

Tim
:-) I did that initially but i was faced with the problem that getElementsByName IS a supported function, IE has it, it just doesn't do what you expect it to do. It has the following odd behaviour
(a) It Returns both mathcing NAMES and for some reason IDS which wasn't a problem for me
(b) It won't return objects created and inserted into the DOM by javascript (this was a problem)

So I have to either override the code of all browsers or just do IE by useragent testing which as you say is not the best way in the world to do things.

Disqus for Domi-No-Yes-Maybe