With the HTML Dom, JavaScript can access all the elements of an HTML document.
The HTML dom (Document Object Model)
When a Web page is loaded, the browser createsDOcumentOBjectMOdel of the page.
TheHTML domModel is constructed as a treeObjects
The html dom tree
With a programmable object model, JavaScript gets all the power it needs to create dynamic HTML:
- Javascript can change all the HTML elements in the page
- Javascript can change all the HTML attributes in the page
- Javascript can change all the CSS styles in the page
- Javascript can react to all the events in the page
Finding HTML elements
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
- Finding HTML elements by ID
- Finding HTML elements by Tag Name
- Finding HTML elements by Class Name
Finding HTML elements by ID
The easiest way to find HTML elements in the Dom, is by using the element ID.
This example finds the element with ID = "Intro ":
Example
VaRX = Document. getelementbyid ("Intro ");
If the element is found, the method will return the element as an object (in X ).
If the element is not found, X will contain null.
Finding HTML elements by Tag Name
This example finds the element with ID = "Main", and then finds all <p> elements inside "Main ":
Example
VaRX = Document. getelementbyid ("Main ");VaRY = x. getelementsbytagname ("p ");
Notice:Finding elements by class name does not work in Internet Explorer 5, 6, 7, and 8.