With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
In the next chapters of this tutorial you will learn:
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
The HTML DOM is a standard object model and programming interface for HTML. It defines:
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
HTML DOM methods are actions you can perform (on HTML Elements)
HTML DOM properties are values (of HTML Elements) that you can set or change
The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).
The following example changes the content (the innerHTML) of the <p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The innerHTML property can be used to get or change any HTML element, including <html> and <body>. |
With the HTML DOM, the document object is your web page.
In the HTML DOM object model, the document object represents your web page.
The document object is the owner of all other objects in your web page.
If you want to access objects in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.
The next chapters demonstrate the methods.
Method |
Description |
document.getElementById() |
Find an element by element id |
document.getElementsByTagName() |
Find elements by tag name |
document.getElementsByClassName() |
Find elements by class name |
Method |
Description |
element.innerHTML= |
Change the inner HTML of an element |
element.attribute= |
Change the attribute of an HTML element |
element.setAttribute(attribute,value) |
Change the attribute of an HTML element |
element.style.property= |
Change the style of an HTML element |
Method |
Description |
document.createElement() |
Create an HTML element |
document.removeChild() |
Remove an HTML element |
document.appendChild() |
Add an HTML element |
document.replaceChild() |
Replace an HTML element |
document.write(text) |
Write into the HTML output stream |
Method |
Description |
document.getElementById(id).onclick=function(){code} |
Adding event handler code to an onclick event |
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
Method |
Description |
DOM |
document.anchors |
Returns all <a> with a value in the name attribute |
1 |
document.applets |
Returns all <applet> elements (Deprecated in HTML5) |
1 |
document.baseURI |
Returns the absolute base URI of the document |
3 |
document.body |
Returns the <body> element |
1 |
document.cookie |
Returns the document's cookie |
1 |
document.doctype |
Returns the document's doctype |
3 |
document.documentElement |
Returns the <html> element |
3 |
document.documentMode |
Returns the mode used by the browser |
3 |
document.documentURI |
Returns the URI of the document |
3 |
document.domain |
Returns the domain name of the document server |
1 |
document.domConfig |
Returns the DOM configuration |
3 |
document.embeds |
Returns all <embed> elements |
3 |
document.forms |
Returns all <form> elements |
1 |
document.head |
Returns the <head> element |
3 |
document.images |
Returns all <image> elements |
1 |
document.implementation |
Returns the DOM implementation |
3 |
document.inputEncoding |
Returns the document's encoding (character set) |
3 |
document.lastModified |
Returns the date and time the document was updated |
3 |
document.links |
Returns all <area> and <a> elements value in href |
1 |
document.readyState |
Returns the (loading) status of the document |
3 |
document.referrer |
Returns the URI of the referrer (the linking document) |
1 |
document.scripts |
Returns all <script> elements |
3 |
document.strictErrorChecking |
Returns if error checking is enforced |
3 |
document.title |
Returns the <title> element |
1 |
document.URL |
Returns the complete URL of the document |
1 |
This page teaches you how to find and access HTML elements in an HTML page.
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
The easiest way to find HTML elements in the DOM, is by using the element id.
This example finds the element with id="intro":
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.
This example finds the element with id="main", and then finds all <p> elements inside "main":
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
If you want to find all HTML elements with the same class name. Use this method:
document.getElementsByClassName("intro");
The example above returns a list of all elements with class="intro".
Finding elements by class name does not work in Internet Explorer 5,6,7, and 8. |
This example finds the form element with id="frm1", in the forms collection, and displays all element values:
var x = document.getElementById("frm1");
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
The HTML DOM allows JavaScript to change the content of HTML elements.
JavaScript can create dynamic HTML content:
Date: Mon Oct 27 2014 19:55:55 GMT+0530 (India Standard Time)
In JavaScript, document.write() can be used to write directly to the HTML output stream:
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Never use document.write() after the document is loaded. It will overwrite the document. |
The easiest way to modify the content of an HTML element is by using 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 a <p> element:
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
This example changes the content of an <h1> element:
<!DOCTYPE html>
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element = document.getElementById("header");
element.innerHTML = "New Header";
</script>
</body>
</html>
Example explained:
To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute=new value
This example changes the value of the src attribute of an <img> element:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Example explained:
The HTML DOM allows JavaScript to change the style of HTML elements.
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when the user clicks a button:
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
HTML DOM allows JavaScript to react to HTML events.
Mouse Over Me
Click Me
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick=JavaScript
Examples of HTML events:
In this example, the content of the <h1> element is changed when a user clicks on it:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
In this example, a function is called from the event handler:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
To assign events to HTML elements you can use event attributes.
Assign an onclick event to a button element:
<button onclick="displayDate()">Try it</button>
In the example above, a function named displayDate will be executed when the button is clicked.
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = function(){ displayDate() };
</script>
In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
The function will be executed when the button is clicked.
The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
<body onload="checkCookies()">
The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.
<input type="text" id="fname" onchange="upperCase()">
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element.
A simple onmouseover-onmouseout example:
Mouse Over Me
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
A simple onmousedown-onmouseup example:
Add an event listener that fires when a user clicks a button:
document.getElementById("myBtn").addEventListener("click", displayDate);
The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
You can add many event handlers to one element.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is seperated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown").
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.
Note that you don't use the "on" prefix for the event; use "click" instead of "onclick". |
Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", function(){ alert("Hello World!"); });
You can also refer to an external "named" function:
Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
The addEventListener() method allows you to add many events to the same element, without overwriting existing events:
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
You can add events of different types to the same element:
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that supports events, like the xmlHttpRequest object.
Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:
element.addEventListener("click", function(){ myFunction(p1, p2); });
There are two ways of event propagation in the HTML DOM, bubbling and capturing.
Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element's "click" event should be handled first?
In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is handled first, then the <div> element's click event.
In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will be handled first, then the <p> element's click event.
With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:
addEventListener(event, function, useCapture);
The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.
document.getElementById("myP").addEventListener("click", myFunction, true);
document.getElementById("myDiv").addEventListener("click", myFunction, true);
The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:
element.removeEventListener("mousemove", myFunction);
The numbers in the table specifies the first browser version that fully supports these methods.
Method |
|
|
|
|
|
addEventListener() |
1.0 |
9.0 |
1.0 |
1.0 |
7.0 |
removeEventListener() |
1.0 |
9.0 |
1.0 |
1.0 |
7.0 |
Note: The addEventListener() and removeEventListener() methods are not supported in IE 8 and earlier versions and Opera 7.0 and earlier versions. However, for these specific browser versions, you can use the attachEvent() method to attach an event handlers to the element, and the detachEvent() method to remove it:
element.attachEvent(event, function);
element.detachEvent(event, function);
Cross-browser solution:
var x = document.getElementById("myBtn");
if (x.addEventListener) { // For all major browsers, except IE 8 and earlier
x.addEventListener("click", myFunction);
} else if (x.attachEvent) { // For IE 8 and earlier versions
x.attachEvent("onclick", myFunction);
}
With the HTML DOM, you can navigate the node tree using node relationships.
According to the W3C HTML DOM standard, everything in an HTML document is a node:
With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
New nodes can be created, and all nodes can be modified or deleted.
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
From the HTML above you can read:
and:
You can use the following node properties to navigate between nodes with JavaScript:
A common error in DOM processing is to expect an element node to contain text.
In this example: <title>DOM Tutorial</title>, the element node <title> does not contain text. It contains a text node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property, or the nodeValue.
In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.
The following example collects the node value of an <h1> element and copies it into a <p> element:
<html>
<body>
<h1 id="intro">My First Page</h1>
<p id="demo">Hello!</p>
<script>
var myText = document.getElementById("intro").childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
</body>
</html>
In the example above, getElementById is a method, while childNodes and nodeValue are properties.
In this tutorial we use the innerHTML property. However, learning the method above is useful for understanding the tree structure and the navigation of the DOM.
Using the firstChild property is the same as using childNodes[0]:
<html>
<body>
<h1 id="intro">My First Page</h1>
<p id="demo">Hello World!</p>
<script>
myText = document.getElementById("intro").firstChild.nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
</body>
</html>
There are two special properties that allow access to the full document:
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.documentElement</b> property.</p>
</div>
<script>
alert(document.documentElement.innerHTML);
</script>
</body>
</html>
The nodeName property specifies the name of a node.
Note: nodeName always contains the uppercase tag name of an HTML element.
The nodeValue property specifies the value of a node.
The nodeType property returns the type of node. nodeType is read only.
The most important node types are:
Element type |
NodeType |
Element |
1 |
Attribute |
2 |
Text |
3 |
Comment |
8 |
Document |
9 |
Adding and Removing Nodes (HTML Elements)
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
This code creates a new <p> element:
var para = document.createElement("p");
To add text to the <p> element, you must create a text node first. This code creates a text node:
var node = document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
var element = document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);
The appendChild() method in the previous example, appended the new element as the last child of the parent.
If you don't want that you can use the insertBefore() method:
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
</script>
To remove an HTML element, you must know the parent of the element:
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
This HTML document contains a <div> element with two child nodes (two <p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
var parent = document.getElementById("div1");
Find the <p> element with id="p1":
var child = document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);
It would be nice to be able to remove an element without referring to the parent. |
Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
var child = document.getElementById("p1");
child.parentNode.removeChild(child);
To replace an element to the HTML DOM, use the replaceChild() method:
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para,child);
</script>
A node list is a collection of nodes
The getElementsByTagName() method returns a node list. A node list is an array-like collection of nodes.
The following code selects all <p> nodes in a