Thursday, August 2, 2007

Javascript getElementById

Javascript document.getElementById
If you want to quickly access the value of an HTML input give it an id and your life gets a lot easier. This small script below will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.

function notEmpty(){
var myTextField = document.getElementById('myText');
if(myTextField.value != "")
alert("You entered: " + myTextField.value)
else
alert("Would you please enter some text?")
}

Things to Remember About getElementById

When using the getElementById function you need to remember a few things to ensure that everything goes smoothly. You always need to remember that getElementById is a method (or function) of the document object. This means you can only access it by: document.getElementById.

Also, be sure that you set your HTML elements' id attributes if you want to be able to use this function. Without an id you'll be dead in the water.

If you want to access the text within a non-input HTML element, then you are going to have to use the innerHTML property, instead of value. The next lesson goes into more detail about the uses of innerHTML.

No comments: