Referencing the FOR property of the HTML LABEL element using JavaScript

24 August 2006 - Permanent link - Categories: implementation

In javascript, I needed to compare the "for" attribute of a LABEL with the ID of an input object to see if I'm looking at the LABEL associated with that radio button / checkbox.

Programmatically, it doesn't work to say something like

if( theLabel.for == theRadio.id ) 

because for is a reserved word in javascript.

So after some investigation (spitting out every single property of the LABEL element and looking to see how the "for" is referred to programmatically), I learned that the way to refer to the FOR attribute with JavaScript is with the htmlFor property:

if( theLabel.htmlFor == theRadio.id )