tags:

views:

88

answers:

3

Hi! I'm a JS beginner. I posted this question because I've been trying to find a solution for 2 hours (it's 3:00am and I'm dying to go to bed). So thanks for understanding.

I want to get the child node of the tagname div. Then alert the name (txtPhone).

<div class="formfield">
  <input id="txtPhone" name="txtPhone" />

So:

alert(document.getElementsByTagName("div")...?);

thanks a lot!

+1  A: 

Using just JavaScript, the property you're after is firstChild.

To alert the name of the element:

alert(document.getElementsByTagName("div")[0].firstChild.name);

Note that you're using getElementsByTagName which returns an array of all div elements - in my above example, I'm accessing the first element from this set, so this will only return the correct link if your div is the first one on the page.

To get around this, I'd suggest giving the div tag you want to target an id, and then using getElementById("id") instead:

<div class="formfield" id="divPhone">
    <input id="txtPhone" name="txtPhone" />

and

alert(document.getElementsById("divPhone").firstChild.name);

If you actually want to target a group of elements, I'd suggest using jQuery's selectors to target the specific elements, such as $(".formfield").firstChild.name

Dexter
nope, still not doing it. it prompts "undefined".
sombe
sorry, I didn't notice that you were using getElementsByTagName.. see modifications above
Dexter
thank you very much!!
sombe
A: 

This should do it:

alert(document.getElementByTagName("div")[0].getElementsByTagName("input")[0].name));

Notice that in your example you have tab/space character after the div? Some browsers (Firefox and not IE from memory) will consider that whitespace as a text node. So firstChild will be set to the text node that contains whitespace in those browsers, which you probably don't want to happen.

Matthew Lock
+1  A: 

I can't leave a comment yet, but I just wanted to add to Matthew's post - it's actually Chrome (and other webkit browsers???) that do that, not Firefox (but you were right about not IE). I just ran into that issue with a site that was for some strange reason using childNodes[0] to get a specific element from a div's collection, rather than just using getElementById (since it knows the ID). It took me forever to figure out what the problem was, until I stepped through and watched exactly what was going on in each line of code on each browser.

Charles Boyung