node.getAttribute('for');

9th January 2005

This is a weird one. Usually when I find a browser bug, or at least something that looks a little like a bug, other people have already found it, documented it and come up with workarounds. This however seems to have gone pretty much unnoticed? Maybe it’s too insignificant for people to care…

I stumbled across this while working on a simple little form validation script. It turns out that in Internet Explorer versions 5.x and 6 on Windows the getAttribute() method always returns null when trying to find a for attribute.

In case you’ve not encountered it before the for attribute can be used in a label tag to associate the label with a form field. This association is made by having the value of the for attribute match the value of the id attribute of the form field. For example,

<label for="name">Name:</label>
<input type="text" id="name" name="name">

So if you want to extract this attribute in IE you can use the attributes array instead. Another alternative would be the getAttributeNode() method which is supported in IE 6 and correctly finds the for attribute,

var forAttribute = labelNode.getAttributeNode('for').value;

However it is also unsupported in IE 5.x. It should also be noted that the attributes array works slightly differently in IE 5.x than it does in more modern browsers. In IE 5.x you can use

var forAttribute = labelNode.attributes['for'];

Whereas in other browsers you need,

var forAttribute = labelNode.attributes['for'].value;

Updated

Ah, it seems there is a simple way to do this avoiding using getAttribute,

var forAttribute = labelNode.htmlFor;

Should return the value of the for attribute across all browsers.

Permalink. Posted on 9th January 2005 in Browsers, JavaScript.

Comments

There are currently no comments for this item.

Sorry, comments for this item are currently closed.

Of Interest

Hangouts

Listening