It turns out that getElementsByName() doesn't work very well in IE. To work around this, I've created a method that extends the document model that will work with IE.
I also cleaned up some missing semicolons because I've been coding in Ruby all day.
If you need to group elements, the "class" attribute makes much more sense and is applicable to most HTML elements. Using the "name" attibute on divs results in invalid code unless you have created your own custom doctype.
The reason I used this hack makes it perfectly justifiable. I have several different groups of elements that will be using the exact same class, because they are identical in appearance. However, the groups need to be treated differently. At the time, a name sounded like the best idea.
I can now see how this could be redone with classes. Not sure it makes this bad code, but hey.
There is nothing wrong with how IE handles the getElementsByName
According to the HTML 4.01 spec, the only elements that support NAME attributes are BUTTON, TEXTAREA, APPLET, SELECT, FORM, FRAME, IFRAME, IMG, A, INPUT, OBJECT, MAP, PARAM and META. So to place a NAME inside a DIV is actually invalid HTML.
There's nothing wrong with Firefox's handling of 'name', so there's no need to create this ugly code. divs are not allowed to have a name attribute. If any browser supports such a thing, it is incorrect.
I also cleaned up some missing semicolons because I've been coding in Ruby all day.
document.getElementsByNameIE = function(tagName,elementName) {
matchingTags = document.getElementsByTagName(tagName);
elementList = new Array;
for(i=0; i < matchingTags.length; i++) {
if( matchingTags[i].name == elementName ) {
elementList.push(matchingTags[i]);
}
}
return elementList;
}
function meFirst(object) {
activeDiv = object.id;
divGroup = object.getAttribute("name");
allMyDivs = document.getElementsByName(divGroup);
if( allMyDivs.length == 0 ) {
allMyDivs = document.getElementsByNameIE("div",divGroup);
}
for(i=0; i < allMyDivs.length; i++ ) {
var newContent = "";
if( allMyDivs[i].id == activeDiv ) {
newContent = "I rule!!";
} else {
newContent = "Click me next!!";
}
allMyDivs[i].innerHTML = newContent;
}
}
I can now see how this could be redone with classes. Not sure it makes this bad code, but hey.
According to the HTML 4.01 spec, the only elements that support NAME attributes are BUTTON, TEXTAREA, APPLET, SELECT, FORM, FRAME, IFRAME, IMG, A, INPUT, OBJECT, MAP, PARAM and META. So to place a NAME inside a DIV is actually invalid HTML.