JavaScript HTML DOM
Through the HTML DOM, all elements of the JavaScript HTML document can be accessed.
HTML DOM (Document Object Model)
When the web page is loaded, the browser creates the Document Object Model of the page.
The HTML DOM model is structured as a tree of objects :
HTML DOM tree
Through the programmable object model, JavaScript has gained enough power to create dynamic HTML.
JavaScript can change all HTML elements in the page
JavaScript can change all HTML attributes in the page
JavaScript can change all CSS styles in the page
JavaScript can react to all events in the page
Find HTML elements
Usually, 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:
Find HTML element 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 finds the id="intro" element:
Example
var x=document.getElementById("intro");
If the element is found, the method will return it as an object (in x).
If the element is not found, then x will contain null.
Find HTML elements by tag name
This example finds the element with id="main", and then finds all <p> elements in the id="main" element:
Example
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 with class="intro":
Example
var x=document.getElementsByClassName("intro");
HTML DOM tutorial
In the remainder of this tutorial, you will learn:
How to change the content of HTML elements (innerHTML)
How to change the style of HTML elements (CSS)
How to react to HTML DOM events
How to add or remove HTML elements