Javascript accessing elements
Javascript provides the ability for getting the value of an element on a webpage as well as dynamically changing the content within an element.
This tutorial focuses on:
- Getting the value of an element
- Changing the content within an element
Getting the value of an element
To get the value of an element, the getElementById method of the document object is used. For this method to get the value of an element, that element has to have an id given to it through the id attribute.
NOTE: Since getElementById() is a method of the document object, you can access it only with the document. prefix -- document.getElementById();
NOTE: To use getElementById() to access an element, be sure to set the id attribute of any element(s) you want to access this way, otherwise it will not work.
NOTE: To access a non-input element through getElementById(), you will have to use the innerHTML property (scroll down to read about the innerHTML property).
Changing the content within an element
To change the content within an element, use the innerHTML property. Using this property, you could replace the text in paragraphs, headings and other elements based on several things such as a value the user enters in a textbox. For this property to change the content within an element, that element has to have an 'id' given to it through the id attribute.
You can also change the text of elements based on user input: