I believe that there is not any short and direct way to access the attached label corresponding to an input field using javascript. You can access the attached label via CSS (with some tweaks in layout) but in javascript, you have to set up a few lines of code. To use this code, the layout also has a requirement that all the attached label should go before the input field (spaces in between are allowed). This code just use the previousSibling
property of a DOM element with some other DOM stuffs. Here is the detail:
function getLabelFromInputID(inputID){
var prevSib = document.getElementById(inputID).previousSibling;
//remove the spaces if any exists
while(prevSib.nodeName=='#text') prevSib=prevSib.previousSibling;
if(prevSib.getAttribute('for') != inputID) prevSib = null;
return prevSib;
}
Use the getLabelFromInputID
function to access the attached label from the corresponding input field's ID. Note that the label should have for
attribute set-up correctly (this is the standard and common practice).
Here is the Fiddle Demo. In this demo, you just try clicking on the page to see it in action.