Get a Form Element's Label with JavaScript
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.
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.
- Free Useful Javascripts
Links to articles that give free javascript code or javascript examples.
- Altering CSS Class Attributes with JavaScript
- Change HTML Styles with JavaScript
- Select Some Checkboxes JavaScript Function
- Select All Checkboxes in a Form with JavaScript
- Get a Form Element's Label with JavaScript
- Select Radio Inputs JavaScript
- UseMaps Crash IE When Changed
- Hide Select Menus JavaScript
- Manipulating Element Styles Based on CSS Classes Using Prototype
- Compare Values with Arbitrary Comparison Operator
- Related Topics