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=""></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
return inputElem.parentNode;
var labels=document.getElementsByTagName("label"),i;
for( i=0; i<labels.length;i++ ){
return labels[i];
return false;


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:'red';

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


No HTML Tags are permitted.

Wall Worm plugins and scripts for 3ds Max