Get a Form Element's Label with JavaScript

Posted Jul 7, 2009
Last Updated Nov 12, 2011

This JavaScript finds the label for a form element, which is helpful for dynamically highlighting or changing a label based on user input.

function smo_input_get_label(inputElem) returns the label element object of a form element if the element has a label. If there is no label for the element, the function returns false.

An example of the code in use follows. To see how it works, simply hit View Source in your browser.


Label Demonstration

Copy the code below to use this function in your page. Paste it into a JavaScript file that your web page uses, or paste it inside a script tag in the head of your HTML. You can also paste

<script type="text/javascript" src="http://www.shawnolson.net/scripts/labelExample.js"></script>

into the head of your document to make this function work. Please keep the credit comment intact.

function smo_input_get_label(inputElem){
//function created by Shawn Olson at http://www.shawnolson.net
if(inputElem.parentNode){
if(inputElem.parentNode.tagName=='label'){
return inputElem.parentNode;
}
}
var labels=document.getElementsByTagName("label"),i;
for( i=0; i<labels.length;i++ ){
if(labels[i].htmlFor==inputElem.id){
return labels[i];
}
}
return false;
}

Discussion

In my opinion, a future version of JavaScript should innately handle this. The label of a form element should be a property of the element. I would like to see this handled automatically such:

textInput.label.style.color='red';

Unfortunately, this does not work natively. You can probaly extend DOM to make this work... but it should be supported internally by JavaScript.

Comment

No HTML Tags are permitted.

Angry Teapot Level Design Awards

Newsletter Subscription