Through the HTML DOM, you can access all the elements of a JavaScript HTML document.
HTML DOM (Document Object model)
When the page is loaded, the browser creates the Document Object model for the page.
The HTML DOM model is constructed as a tree of objects:
Through the programmable object model, JavaScript has acquired enough power to create dynamic HTML.
- JavaScript can change all HTML elements in a page
- JavaScript can change all HTML attributes in a page
- JavaScript can change all CSS styles in a page
- JavaScript can respond to all events in a page
Find HTML elements
Typically, through JavaScript, you need to manipulate HTML elements.
In order to do this, you must first find the element. There are three ways to do this:
- Find HTML elements by ID
- Find HTML elements by tag name
- Find HTML elements by class name
- Find HTML elements by ID
The easiest way to find HTML elements in the DOM is by using the ID of the element.
This example looks for the id= "Intro" element:
Instance
var X=document.getelementbyid ("Intro");
If the element is found, the method returns the element as an object (in X).
If the element is not found, X will contain null.
find HTML elements by tag name
This example finds the element of id= "main" and then looks for all <p> elements in the id= "main" element:
Instance
var X=document.getelementbyid ("main");
var y=x.getelementsbytagname ("P");
Find HTML elements by class name
This example uses the Getelementsbyclassname function to find elements of the class= "Intro":
Instance
var x=document.getelementsbyclassname ("Intro");
Change HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
change HTML output stream
JavaScript is able to create dynamic HTML content:
Today's date is: Wed Oct 2015 14:43:25 gmt+0800 (China Standard Time)
In JavaScript, document.write () can be used to write content directly to HTML output.
Instance
Lamp should never use document.write () after the document is loaded. This overwrites the document.
Change HTML Content
The simplest way to modify HTML content is to use the InnerHTML property.
To change the contents of an HTML element, use this syntax:
document.getElementById (ID). innerhtml=new HTML
This example changes the contents of the <p> element:
Instance
This example changes the contents of the Instance
Example Explanation:
- The HTML document above contains the elements of the id= "header"
- We use the HTML DOM to get the elements of the id= "header"
- JavaScript changes the content of this element (InnerHTML)
Changing HTML Properties
To change the attributes of an HTML element, use this syntax:
document.getElementById (ID). attribute=new value
This example changes the SRC attribute of the element:
Instance
Example Explanation:
- The HTML document above contains the elements of id= "image"
- We use the HTML DOM to get the elements of id= "image"
- JavaScript changes the attributes of this element (change "smiley.gif" to "landscape.jpg")