JavaScript HTML DOM
JavaScript HTML DOM
With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
"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."
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
HTML DOM properties are values (of HTML Elements) that you can set or change.
A property is a value that you can get or set (like changing the content of an HTML
element).
Example
The following example changes the content (the innerHTML) of the <p> element
with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
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>.
The HTML DOM document object is the owner of all other objects in your web page.
If you want to access any element 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.
Method Description
ADVERTISEMENT
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
Property Description D
O
M
document.applets Deprecated 1
document.domConfig Obsolete. 3
To do so, you have to find the elements first. There are several ways to do this:
If the element is found, the method will return the element as an object (in element).
If the element is not found, element will contain null.
Example
const x = document.getElementById("main");
const y = x.getElementsByTagName("p");
Example
const x = document.querySelectorAll("p.intro");
Example
const x = document.forms["frm1"];
let text = "";
for (let 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.
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
document.write()
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Submit
If a form field (fname) is empty, the required attribute prevents this form from being
submitted:
Automatic HTML form validation does not work in Internet Explorer 9 or earlier.
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different
ways.
Server side validation is performed by a web server, after input has been sent to the
server.
Client side validation is performed by a web browser, before input is sent to a web
server.
Example
<html>
<body>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
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>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example
<div id ="container">
<div id ="animate">My animation will go here</div>
</div>
Style the Elements
The container element should be created with style = "position: relative".
Example
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
ADVERTISEMENT
Animation Code
JavaScript animations are done by programming gradual changes in an element's style.
The changes are called by a timer. When the timer interval is small, the animation looks continuous.
Example
id = setInterval(frame, 5);
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
Create the Full Animation Using
JavaScript
Example
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
Mouse Over Me
Click Me
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:
onclick=JavaScript
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
document.getElementById("myBtn").addEventListener("click", displayDate);
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" or any other HTML DOM Event.)
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".
Example
function myFunction() {
alert ("Hello World!");
}
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:
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.
Node Relationships
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>
and:
ADVERTISEMENT
Navigating Between Nodes
You can use the following node properties to navigate between nodes with JavaScript:
parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
Example:
The element node <title> (in the example above) does not contain text.
The value of the text node can be accessed by the node's innerHTML property:
myTitle = document.getElementById("demo").innerHTML;
Accessing the innerHTML property is the same as accessing the nodeValue of the first
child:
myTitle = document.getElementById("demo").firstChild.nodeValue;
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>
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").innerHTML;
</script>
</body>
</html>
Example
<html>
<body>
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").firstChild.nodeValue;
</script>
</body>
</html>
Example
<html>
<body>
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").childNodes[0].nodeValue;
</script>
</body>
</html>
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.
DOM Root Nodes
There are two special properties that allow access to the full document:
Example
<html>
<body>
<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.body</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = document.body.innerHTML;
</script>
</body>
</html>
Example
<html>
<body>
<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.documentElement</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = document.documentElement.innerHTML;
</script>
</body>
</html>
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
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").nodeName;
</script>
Note: nodeName always contains the uppercase tag name of an HTML element.
Example
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").nodeType;
</script>
TEXT_NODE 3 W3Schools
Type 2 is deprecated in the HTML DOM (but works). It is not deprecated in the XML DOM.
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
To add text to the <p> element, you must create a text node first. This code creates a text
node:
Then you must append the text node to the <p> element:
para.appendChild(node);
element.appendChild(para)
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>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
Example
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const elmnt = document.getElementById("p1"); elmnt.remove();
</script>
Example Explained
The HTML document contains a <div> element with two child nodes (two <p> elements):
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
elmnt.remove();
The remove() method does not work in older browsers, see the example below on how to
use removeChild() instead.
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.removeChild(child);
</script>
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>
parent.removeChild(child);
Here is a common workaround: Find the child you want to remove, and use
its parentNode property to find the parent:
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.replaceChild(para, child);
</script>
Example
myCollection[1]
Example
myCollection.length
The length property is useful when you want to loop through the elements in a collection:
Example
You can loop through the list and refer to the elements with a number (just like an array).
However, you cannot use array methods like valueOf(), pop(), push(), or join() on an
HTMLCollection.