[thelist] Reading out the "for" atttribute via Javascript

liorean liorean at gmail.com
Thu Feb 24 12:58:33 CST 2005


On Thu, 24 Feb 2005 18:39:23 +0100 (CET), Chris Heilmann
<lists at onlinetools.org> wrote:
> {tip type="DOM Javascript" author="Chris Heilmann"}
> When reading out the "for" attribute of a label element, IE and Gecko part
> ways - once again.
> Firefox grabs yourobject.getAttribute('for'), whereas IE needs
> yourobject.getAttribute('htmlFor').
> Both (and Opera) can use:
> var
> labelfor=labels[i].getAttribute('for')?labels[i].getAttribute('for'):labels[i].getAttribute('htmlFor');
> 
> An example:
> labels=document.getElementsByTagName('label');
> for(var i=0;i<labels.length;i++)
> {
> var
> labelfor=labels[i].getAttribute('for')?labels[i].getAttribute('for'):labels[i].getAttribute('htmlFor');
> fieldnames[labelfor]=labels[i].firstChild.nodeValue;
> }
> {/tip}

<tip type="DOM JavaScript" author="liorean">If you want to read out or
write to the 'for' attribute of a 'label' element in an HTML document,
don't try to use Element.prototype.getAttribute and
Element.prototype.setAttribute. Instead do both through accessing the
DOM1HTML binding, HTMLLabelElement.prototype.htmlFor.

This mean that instead of:

    var
        forAttribute = label.getAttribute('for') ||
            label.getAttribute('htmlFor');

You can write like this:

    var
        forAttribute = label.htmlFor;



And, conversely, if you want to write to it instead of read from it,
you can write like this:

    label.htmlFor=value;

</tip>
-- 
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>


More information about the thelist mailing list