5

I have the following HTML

            <div>
                <label for="username">Username:</label>
                <input type="text" name="username" id="username" />
                <span>some text here</span>
            </div>

now I have referenced the input "username" in javaScript using getElementById rather easily but I need to locate (via javascript) the text of the label associated with the input, I'm thinking something like this:

document.getElement(thisName).parent.getElementsByTagName('label')[0].innerHTML;

Any help is appreciated

Mark Sandman
  • 3,293
  • 12
  • 40
  • 60

2 Answers2

7

I think this is what you want:

document.getElementById('username').parentNode.getElementsByTagName('label')[0].innerHTML;
Karolis
  • 9,396
  • 29
  • 38
0

You can use the .previousElementSibling property to get the previous sibling element.

If that property isn't supported, you can use a function to emulate it.

var inp = document.getElementById('username');

var lab = inp.previousElementSibling || previousElementSibling( inp );

function previousElementSibling( el ) {
    while( el && (el = el.previousSibling) && el.nodeType !== 1 );
    return el;
}
user113716
  • 318,772
  • 63
  • 451
  • 440