The HTML DOM provides access to all elements of a JavaScript HTML document.
HTML DOM (Document Object Model)
When a web page is loaded, the browser creates the page's Document Object Model.
The HTML DOM model is constructed as a tree of objects:
Through the programmable object model, JavaScript gained sufficient power to create dynamic HTML.
Find HTML element
Typically, with 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:
The easiest way to find an HTML element in the DOM is by using the element's id.
This example finds the element with id="intro":
Example
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 with id="main" and then finds all
elements within the id="main" element:
Example
var x=document.getElementById("main"); var y=x.getElementsByTagName("p");
Find HTML element by class name
This example uses the getElementsByClassName function to find elements with class="intro":
Example
var x=document.getElementsByClassName("intro");
Change HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
Change HTML output stream
JavaScript can create dynamic HTML content:
Today’s date is: Wed Oct 21 2015 14:43:25 GMT 0800 (China Standard Time)
In JavaScript, document.write() can be used to write content directly to the HTML output stream.
Example
<!DOCTYPE html> <html> <body> <script> document.write(Date()); </script> </body> </html>
lamp Never use document.write() after the document has finished loading. This will overwrite the document.
Change HTML content
The simplest way to modify HTML content is to use the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML=new HTML
This example changes the content of the
element:
Example
<html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="New text!"; </script> </body> </html>
This example changes the content of the
<!DOCTYPE html> <html> <body> <h1 id="header">Old Header</h1> <script> var element=document.getElementById("header"); element.innerHTML="New Header"; </script> </body> </html>
Explanation with examples:
Change HTML attributes
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:
Example
<!DOCTYPE html> <html> <body> <img id="image" src="smiley.gif" alt="Detailed explanation of the basic ways of operating HTML DOM with JavaScript_Basic knowledge" > <script> document.getElementById("image").src="landscape.jpg"; </script> </body> </html>
Explanation with examples: