[Javascript] accessing a <label>

Mike Dougherty mdougherty at pbp.com
Sun Jun 3 21:25:37 CDT 2007


On 6/3/07, Rick Pasotto <rick at niof.net> wrote:
> 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
> <label for="name">Your Name:</label>
> <input type="text" id="name" name="name" size="30"/>

The spec says either use for label is correct.  I think it depends on
use which makes more sense.

> function getLabelById(arg) {
>         var labels = document.getElementsByTagName("label");
>         for (i=0;i<labels.length;i++) {

> Can anyone think of a better way?

Can you just Id your labels?
<label id="Lname" for="name">Your Name:</label>
<input type="text" id="name" name="name" size="30"/>

var obj = document.getElementById("L"+inputId);

other than direct access to the label by id, the only slightly better
way than your iterative solution would be narrow the number of labels
to iterate using some container:  var collection =
document.getElementById("containerId").getElementsByTagName("label");
I like to point out that this usage constrains the results to the
named elements that are children of the containerId element.  It might
not be feasible to do that though, depending on your form.  (although
if your input is in a table, the inputobj.parentNode.parentNode would
be the row object assuming tr/td/input structure)



More information about the Javascript mailing list