View Full Version : Retrieving Label textNode?

Willy Duitt
10-04-2004, 09:55 PM
I know how to use the DOM to create a label:

var label = document.createElement('label');
label.appendChild(document.createTextNode('New Name'));

But I am trying to retrieve the value of a form elements label textNode value... I need to do this without using an id on the label and was hoping to do this thru the input itself...

Although if I wrap the input within the <label><input></label> I can retrieve the textNode thru parentNode.innerHTML... But I need to do this when the label is in another data cell and thus does not share the same parentNode....

<tr><td><label for="firstName">First Name: </label></td></tr>
<tr><td><input type="text" id="firstName" name="firstName"

I've searched and searched without joy...
Any ideas?


10-04-2004, 10:35 PM
The fastest solution is probably to use document.getElementsByTagName method to get all label elements, and then search the htmlFor property of each of them until you find one that matches the id of your form control.

Willy Duitt
10-04-2004, 10:46 PM
Ok, I'll try that but I was hoping to do this more directly....

Once, I thought I did something with a camelCase labelFor getAttribute but can not find a copy of that script....


10-04-2004, 10:53 PM
Well, if you want better efficiency you can create a static lookup table, under the highly likely circumstance that you don't dynamically add or remove label elements to the document.