JavaScript Document Object Model (DOM)
Document Object ModelThe Document Object Model (DOM) provides a way to access and alter the contents of Hypertext Markup Language (HTML) documents. The DOM represents HTML documents in an uprooted tree-like structure because the root of the tree is on the top.
For example, consider the HTML document:
<!doctype html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>Here's some text.</p>
<p>Here's more text.</p>
<p>Link to the <a href="http://www.w3.org">W3</a></p>
</body>
</html>
The HTML when viewed in the tree structure of the DOM is like:
Many HTML elements can have attributes, such as the href attribute of the <a> element. You can both retrieve and set the attributes using the DOM.
Nodes
The DOM represents an HTML document as a hierarchy of nodes. The elements within the tree structure are referred to as nodes or node objects. Any node has relationships to other nodes in the DOM tree.
1. Child Nodes
Nodes at the level below a given node are known as children. For example, the <body> node has three child nodes, all <p> elements, and one of the <p> elements has a child of its own, an <a> element.
2. Parent Nodes
The <body> node is said to be a parent of the <p> nodes. Similarly, the <body> is a child node of the <html> node, and <html> is the parent of the <body> node.
3. Siblings
The <body> node is the sibling of the <head> node because they share the same immediate parent, which is the <html> element. The three <p> nodes are also siblings because they are on the same level.
Descendants
Any nodes under a given node are known as descendants of that node.
Properties of Node
A node has three important properties:
- nodeType
- nodeName
- nodeValue
Selecting Elements
Two primary methods to retrieve elements are: getElementById() and getElementsByTagName().
1. Get Element by ID
The getElementById() method retrieves a specified element of the HTML document and returns a reference to it. To retrieve an element, it must have an id attribute. For example, for HTML:
<p id="my-id">Here is some text.</p>
You can retrieve the <p> elements like:
var p = document.getElementById("my-id");
2. Get Elements by Tag Name
When you need to retrieve more than one element at a time, you can use the getElementsByTagName() method. It returns all the elements of the specified tag type in an array or in a list format. For example, to retrieve all the images (<img> tags) in a document,
var images = document.getElementsByTagName("img");
Then, you can examine the properties of the <img> elements stored in the images variable by looping through them. For example, following code changes the background color of each <td> element within the table when the user clicks the Click To Change Colors link.
function changecolors() {
var a1 = document.getElementsByTagName("td");
var a1Length = a1.length;
for (var i = 0; i < a1Length; i++) {
a1[i].style.background = "#aaabba";
}
}
For the link:
<a href="#" onclick="return changecolors();">Click to Change Colors</a>
That function retrieves all <td> elements by using the getElementsByTagName() method, placing them into the a1 array. Then, the code enumerates this array using a for loop, starting at element 0, and continuing to the end of the array. It uses the a1Length variable, which gets the length of the a1 array in the line preceding the for loop.
3. Query Selector
The JavaScript querySelector() and querySelectorAll() methods are used to find elements based on CSS selectors. The querySelector() method allows you to select the first element that matches one or more CSS selectors. The querySelectorAll() method to select all elements that match a CSS selector.
Types of Selectors:
- Universal selector - *
- Type selector - h1
- Class selector - .btn
- ID selector - #logo
- Attribute selector - [attribute] or [attribute=value]
Traversing Elements
The JavaScript contains methods and properties for working with the parent, child and sibling relationship of an HTML document.
1. Parent
To get the parent node of a specified node, use the parentNode property.
2. First Child
To get the first child element of a specified element, use the firstChild property.
3. Last Child
To get the last child element of a node, use the lastChild property.
4. All Children
To get the child element with only the element node type, use the children property.
5. Next Sibling
To get the next sibling of an element, use the nextElementSibling property.
6. Previous Sibling
To get the previous siblings of an element, you use the previousElementSibling property.
Examples
let parent = node.parentNode;
let firstChild = parentElement.firstChild;
let lastChild = parentElement.lastChild;
let children = parentElement.children;
let nextSibling = currentNode.nextElementSibling;
let prevSibling = currentNode.previousElementSibling;
You can iterate through a set of child nodes using the their nextSibling and previousSibling properties. If there are no more siblings, the property returns null. For example, the previousSibling property returns null when used on the first child, and the nextSibling property returns null when used on the last child.
Attributes
Sometimes, you might not know what attributes are available for a given element. The web browser automatically converts attributes of HTML elements to the properties of DOM objects.
To access attributes, use the following methods:
- element.getAttribute(name) - get the attribute value
- element.setAttribute(name, value) - set the value for the attribute
- element.hasAttribute(name) - check for the existence of an attribute
- element.removeAttribute(name) - remove the attribute
The element.attributes property provides a collection of attributes available on a specific element.
Creating Elements
- createElement() - create a new element
- appendChild() - append a node to a list of child nodes of a specified parent node
- textContent - get and set the text content of a node
- innerHTML - get and set the HTML content of an element
You can add elements to a document using the DOM. The createElement() method of the document object creates or adds an element to a document. For example,
var newelement = document.createElement("p");
The variable newelement now has a reference to the new element. To make the element visible, you need to append the element to the document, although usually only after adding text to it. You add an element to a document using the appendChild() method, as:
document.body.appendChild(newelement);
You can append a text node to the <p> element, as:
newelement.appendChild(document.createTextNode("Hello World"));
Deleting Elements
You can remove nodes from a document by using the removeChild() method. For example,
var removeel = document.getElementById("element1");
document.body.removeChild(removeel);
Other Methods
- replaceChild() - replace a child element by a new element.
- cloneNode() - clone an element and all of its descendants.
- after() - insert a node after an element.
- append() - insert a node after the last child node of a parent node.
- prepend() - insert a node before the first child node of a parent node.