Thursday, June 19, 2008

What's in a name ?

Folks, this is going to be yet another of my quick grumblings (you can call it a tech post if you like) connected closely with IE and Javascript yet again. I recently came across a requirement where I had to toggle the visibility certain elements (which happened to be TRs in my case) and not failing the tradition, yet again faced inexplicable problems with IE. Most naturally, I used the function getElementsByName for this purpose. Oh, no! For once, IE cannot be blamed this time around. The method getElementsByName was the core of the recent problem I faced. This method comes is specified as a part of DOM1 Core whereas it has been moved from core to HTML in DOM2 ( Reference). However, the all benevolent FireFox continues to provide this method to all the elements quite unlike its counterpart. So while IE wont accept elements in the DOM structure to be picked up by their names, Firefox gleefully does the same.

Now that we know the problem, what is the solution ? As is the case with most of the javascript fixes, it is a hacky solution which can be easily observed from the code frag given below :

The simple idea is to use some other identifier to recognize the elements that you want to get hold of -

HTML:

tr id="blah_1" name="blah"
tr id="blah_2" name="blah"
tr id="blah_3" name="blah"


Javascript :

var elts = document.getElementsByTagName("TR");

for (i=0; i< elts.length; i++)
{
if(elts[i] != null && elts[i].name != undefined && elts[i].name.indexOf("blah") >= 0)
{
//got the element !!
alert(elts[i].id);
}
}


That's it folks ! If the elements are not of the same tag type, you can as well use .className or any such identifier to fetch the elements that you would want to :)

~Titan.

No comments: