Philip007
Philip007

Reputation: 3230

javascript getElementsByTagName doesn't work

Is there something wrong with the script? or that getElementsbyTagName is deprecated?

<script>
t=document.getElementsByTagName('input')[0];
document.write(t.value);
</script>

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Type here: <input type='text' value="my value is high">

Upvotes: 0

Views: 2160

Answers (1)

Robusto
Robusto

Reputation: 31883

You're trying to do a document.write() presumably before your page is loaded. Therefore, the array returned by getElementsByTagName will be empty because there aren't any tags of any kind available until the document has loaded.

Either handle this from the body.onload event, or else trigger it from some other event. In fact, why would you be trying to get the value of a text input before it could even have any value other than the one you supply (here, 'my value is high'), in which case you could just use that literal value in your document.write()?

I suspect you want to get the value of that input after some user interaction, in which case you might handle the input's onblur event with a function that sets the innerHTML of some other element to the value of the event.currentTarget (which will be your input). So after the user has typed something and exited the input, the value of the input would appear wherever you desire.

Upvotes: 2

Related Questions