JavaScript HTML DOM
Through the HTML DOM, you can access all elements of a JavaScript HTML document.
HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model (DOM) of the page.
The HTML DOM model is constructed as a tree of objects:
HTML DOM Tree
With a programmable object model, JavaScript has the power 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 need to manipulate HTML elements.
To do this, you must first find the elements. There are several ways to do this:
- By id of the HTML element
- By tag name of the HTML element
- By class name of the HTML element
Finding HTML Elements by Id
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 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 within the "main" element:
Example
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
Finding HTML Elements by Class Name
This example finds elements with class="intro" using the function:
Example
var x = document.getElementsByClassName("intro");
HTML DOM Tutorial
In the following sections of this tutorial, you will learn:
- How to change the content of HTML elements (innerHTML)
- How to change the style (CSS) of HTML elements
- How to react to HTML DOM events
- How to add or remove HTML elements