开发者

How to find sibling tag using javascript

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 thinkin开发者_运维知识库g something like this:

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

Any help is appreciated


I think this is what you want:

document.getElementById('username').parentNode.getElementsByTagName('label')[0].innerHTML;


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜