Search code examples
javascripthtmllabel

Find html label associated with a given input


Let's say I have an html form. Each input/select/textarea will have a corresponding <label> with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label.

Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?


Solution

  • First, scan the page for labels, and assign a reference to the label from the actual form element:

    var labels = document.getElementsByTagName('LABEL');
    for (var i = 0; i < labels.length; i++) {
        if (labels[i].htmlFor != '') {
             var elem = document.getElementById(labels[i].htmlFor);
             if (elem)
                elem.label = labels[i];         
        }
    }
    

    Then, you can simply go:

    document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';
    

    No need for a lookup array :)