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:
Example
<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>
Try it Yourself »
Using Events
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
- An element is clicked on
- The page has loaded
- Input fields are changed
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:
Example
<!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>
Try it Yourself »
More Examples
Visibility How to make an element invisible. Do you want to show the element or not?
- JavaScript HTML DOM Events
HTML DOM allows JavaScript to react to HTML events:
Reacting to Events
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:
Examples of HTML events:
- When a user clicks the mouse
- When a web page has loaded
- When an image has been loaded
- When the mouse moves over an element
- When an input field is changed
- When an HTML form is submitted
- When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
Try it Yourself »
In this example, a function is called from the event handler:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}</script>
</body>
</html>
Try it Yourself »
To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
<button onclick="displayDate()">Try it</button>
Try it Yourself »
In the example above, a function named displayDate will be executed when the button is clicked.
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;</script>
Try it Yourself »
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
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.
Example
The onchange Event
The onchange event is 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.
Example
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element:
Mouse Over Me
The onmousedown, onmouseup and onclick Events
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.
Thank You
More Examples
onload
Display an alert box when the page has finished loading.
onfocus
Change the background-color of an input field when it gets focus.
Mouse Events
Change the color of an element when the cursor moves over it.
- JavaScript HTML DOM EventListener
The addEventListener() method
Example
Add an event listener that fires when a user clicks a button:
document.getElementById("myBtn").addEventListener("click", displayDate);
Try it Yourself »
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 separated 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.
Syntax
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".
Add an Event Handler to an Element
Example
Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", function(){ alert("Hello World!"); });
Try it Yourself »
You can also refer to an external "named" function:
Example
Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
Try it Yourself »
Add Many Event Handlers to the Same Element
The addEventListener() method allows you to add many events to the same element, without overwriting existing events:
Example
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
Try it Yourself »
You can add events of different types to the same element:
Example
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Try it Yourself »
Add an Event Handler to the Window Object
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 support events, like the xmlHttpRequest object.
Example
Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
Try it Yourself »
Passing Parameters
When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:
Example
element.addEventListener("click", function(){ myFunction(p1, p2); });
Try it Yourself »
- Event Bubbling or Event Capturing?
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.
Example
document.getElementById("myP").addEventListener("click", myFunction, true);
document.getElementById("myDiv").addEventListener("click", myFunction, true);
Try it Yourself »
The removeEventListener() method
The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:
Example
- JavaScript HTML DOM Navigation
With the HTML DOM, you can navigate the node tree using node relationships.
DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document is a node:
- The entire document is a document node
- Every HTML element is an element node
- The text inside HTML elements are text nodes
- Every HTML attribute is an attribute node
- All comments are comment nodes
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.
- In a node tree, the top node is called the root (or root node)
- Every node has exactly one parent, except the root (which has no parent)
- A node can have a number of children
- Siblings (brothers or sisters) are nodes with the same parent
<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:
- <html> is the root node
- <html> has no parents
- <html> is the parent of <head> and <body>
- <head> is the first child of <html>
- <body> is the last child of <html>
and:
- <head> has one child: <title>
- <title> has one child (a text node): "DOM Tutorial"
- <body> has two children: <h1> and <p>
- <h1> has one child: "DOM Lesson one"
- <p> has one child: "Hello world!"
- <h1> and <p> are siblings
You can use the following node properties to navigate between nodes with JavaScript:
- parentNode
- childNodes[nodenumber]
- firstChild
- lastChild
- nextSibling
- previousSibling
Child Nodes and Node Values
A common error in DOM processing is to expect an element node to contain text.
Example:
<title id="demo">DOM Tutorial</title>
The element node <title> (in the example above) 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:
var myTitle = document.getElementById("demo").innerHTML;
Accessing the innerHTML property is the same as accessing the nodeValue of the first child:
var myTitle = document.getElementById("demo").firstChild.nodeValue;
Accessing the first child can also be done like this:
var myTitle = document.getElementById("demo").childNodes[0].nodeValue;
All the (3) following examples retrieves the text of an <h1> element and copies it into a <p> element:
Example
<html>
<body>
<h1 id="id01">My First Page</h1>
<p id="id02"></p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;</script>
</body>
</html>
Try it Yourself »
Example
<html>
<body>
<h1 id="id01">My First Page</h1>
<p id="id01"></p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").firstChild.nodeValue;</script>
</body>
</html>
Try it Yourself »
Example
<html>
<body>
<h1 id="01">My First Page</h1>
<p id="02">Hello!</p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").childNodes[0].nodeValue;</script>
</body>
</html>
Try it Yourself »
InnerHTML
In this tutorial we use the innerHTML property to retrieve the content of an HTML element.
However, learning the other methods above is useful for understanding the tree structure and the navigation of the DOM.
There are two special properties that allow access to the full document:
- document.body - The body of the document
- document.documentElement - The full document
Example
<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>
Try it Yourself »
Example
<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>
Try it Yourself »
The nodeName Property
The nodeName property specifies the name of a node.
- nodeName is read-only
- nodeName of an element node is the same as the tag name
- nodeName of an attribute node is the attribute name
- nodeName of a text node is always #text
- nodeName of the document node is always #document
Example
<h1 id="id01">My First Page</h1>
<p id="id02"></p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeName;</script>
Try it Yourself »
Note: nodeName always contains the uppercase tag name of an HTML element.
The nodeValue Property
The nodeValue property specifies the value of a node.
- nodeValue for element nodes is undefined
- nodeValue for text nodes is the text itself
- nodeValue for attribute nodes is the attribute value
The nodeType Property
The nodeType property returns the type of node. nodeType is read only.
Example
<h1 id="id01">My First Page</h1>
<p id="id02"></p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeType;</script>
Try it Yourself »
The most important node types are:
| Element type | NodeType |
| Element | 1 |
| Attribute | 2 |
| Text | 3 |
| Comment | 8 |
| Document | 9 |
- javaScript HTML DOM Elements (Nodes)
Adding and Removing Nodes (HTML Elements)
- Creating New HTML Elements (Nodes)
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.
Example
<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>
Try it Yourself »
Example Explained
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:
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);
- Creating new HTML Elements - insertBefore()
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:
Example
<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>
Try it Yourself »
- Removing Existing HTML Elements
To remove an HTML element, you must know the parent of the element:
Example
<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>
Try it Yourself »
The method node.remove() is implemented in the DOM 4 specification.
But because of poor browser support, you should not use it.
Example Explained
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.
But sorry. The DOM needs to know both the element you want to remove, and its 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:
Example
<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>
Try it Yourself »
- JavaScript HTML DOM Node List
A node list is a collection of nodes
HTML DOM Node List
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 document:
Example
var x = document.getElementsByTagName("p");
The nodes can be accessed by an index number. To access the second <p> node you can write:
y = x[1];
Try it Yourself »
Note: The index starts at 0.
HTML DOM Node List Length
The length property defines the number of nodes in a node list:
Example
var myNodelist = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myNodelist.length;
Try it Yourself »
Example explained:
- Get all <p> elements in a node list
- Display the length of the node list
The length property is useful when you want to loop through the nodes in a node list:
Example
Change the background color of all <p> elements in a node list:
var myNodelist = document.getElementsByTagName("p");
var i;
for (i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "red";
}
Try it Yourself »
A node list is not an array!
A node list may look like an array, but it is not. You can loop through the node list and refer to its nodes like an array. However, you cannot use Array Methods, like valueOf() or join() on the node list.