tags:

views:

72

answers:

1

I want to use javascript to find the first textbox in a container, so I can set it to focused, but the textbox could be nested. Is there an easy way I can cycle through until I come across the first textbox?

+5  A: 

document.getElementById('container').getElementsByTagName('textarea')[0].focus();

chelmertz
Isn't this for a textarea
rahul
Is this recursive? So if my container contains a bunch of nested items and the textbox is right at the top of the tree, will it work?
SLC
It works, I just had to change textarea to input. Thanks!
SLC
The [0] ensures it's the first child element with that tag. If you wish to search through elements: var inputs = document.getElementById('container').getElementsByTagName('input');for(var i in inputs){ if(inputs[i].getAttribute('type') == 'text'){ /*inputs[i] is the first input */ /*do something*/ break; /* break so you wont hit more than one input*/ } }
chelmertz