Finding an element on the page can be done using the document.getElementById() or document.getElementByTagName()
method. The first method gives you directly the element back and the
second methods returns all the elements that have the same element
name.
getElementById()
Suppose we have the following HTML document:
<html> <head> <script type="text/javascript"> function displayFirstnameContents() { var firstnameTextfield = document.getElementById('firstname'); alert(firstnameTextfield.value); } </script> </head> <body> <input id="firstname" type="text" value="Ronald"/> <input type="button" onclick="displayFirstnameContents();" value="ClickMe!"/> </body> </html>
This HTML document displays a text field with a button, when you click on the button the button will call the displayFirstnameContents() method which in return will locate the firstname text field on the page. When it has found this textfield it will display the contents of the field.
getElementsByTagName()
Suppose we have the following HTML document:
<html> <head> <script type="text/javascript"> function displayTextfieldsContents() { var textfields = document.getElementsByTagName('input'); for (var index = 0; index < textfields.length; index++) { alert(textfields[index].id + " - " + textfields[index].value); } } </script> </head> <body> <input id="firstname" type="text" value="Ronald"/> <input id="lastname" type="text" value="Mathies"/> <input id="clickMeButton" type="button" onclick="displayTextfieldsContents();" value="ClickMe!"/> </body> </html>
This HTML document displays two text fields on the page along with a
button. When the user clicks on this button the button will call the displayTextfieldsContents() method which in return will locate all the input elements on the page that are of the type input (in this case it means the two text fields and the button). After it has located all the input elements it loops through all the elements and displays the id attribute and the value attribute.
|