Using document.getElementById()

Posted: 2nd December 2010 by admin in programming

With document.getElemebtById() we can have access and modify the properties of any HTML element for instance if we have the following element:

<input id="myText" type="text" />

To access all it’s properties like style or value, we just refer to the element and make the change:

document.getElementById("myText").value = "Hello";

If you put this pieces of code into a page it will not work because there is no action that call the the assigned variable, to make a proper call we should create a function or place a button if you like:

<input id="myText" type="text" /> <input type="button" value="ClickMe" onClick="getValue()" />

function getValue(){
document.getElementById("myText").value = "Hello";

Please notice a couple of things in the code:

We are accessing to the value property and editing it, so no matter what you please on the text field, the moment that you click on the button it will be replaced with the “Hello” string.

And the most important thing is that on the text field you have the “id” element, believe me many times I saw people trying to access an element using the “name” element don’t make this mistake:

<input name="myText" type="text" />

I future posts we will be exploring more complex applications on how to manage and edit HTML elements.