JavaScript HTML DOM
With 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 the page's Document Object Model.
HTML DOM The model is structured asobjecta tree:
HTML DOM Tree
With a programmable object model, JavaScript has gained enough 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 events in the page
Finding HTML Elements
Usually, with JavaScript, you need to manipulate HTML elements.
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
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");
Try it »
If the element is found, the method returns it 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", then finds all the elements in the id="main" element
element:
Example
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
Try it »
Find HTML elements by class name
This example uses the getElementsByClassName function to find elements with class="intro":
Example
var x=document.getElementsByClassName("intro");
Try it »
HTML DOM Tutorial
In the rest of this tutorial, you will learn:
- How to change the content of an HTML element (innerHTML)
- How to change the style of an HTML element (CSS)
- How to react to HTML DOM events
- How to add or remove HTML elements