[Javascript] accessing a <label>
Rick Pasotto
rick at niof.net
Sun Jun 3 20:47:50 CDT 2007
On Sun, Jun 03, 2007 at 06:10:48PM -0600, Nick Wiltshire wrote:
> If the input is directly inside the label (as it should be) and you have a
> reference to the input, the label can be accessed through input.parentNode
>
> On Sunday 03 June 2007 15:00, Rick Pasotto wrote:
> > How do I access the <label> element associated with an <input>?
> > I'd like to add a class to change the background if validation fails.
The input *can* be inside the label thus giving an *implicit* reference
but that doesn't work if the label and the input are, for example, in
different cells of a table. An *explicit* reference using "for=" seems
better to me and is what I was using.
<label for="name">Your Name:</label>
<input type="text" id="name" name="name" size="30"/>
After I posted I found info that resulted in this:
function getLabelById(arg) {
//get all labels
var labels = document.getElementsByTagName("label");
for (i=0;i<labels.length;i++) {
//find the field that the label refers to (using for attribute)
var thisId = labels[i].getAttribute("for");
if ((thisId)==null) { //alert('feckin ie') ... as ever
thisId = labels[i].htmlFor;
}
return thisID;
}
}
Can anyone think of a better way?
--
"Life is like an over long drama through which we sit being nagged
by the vague memories of having read the reviews." -- John Updike
Rick Pasotto rick at niof.net http://www.niof.net
More information about the Javascript
mailing list