What is DOM
The Document Object Model, more commonly referred to as the DOM, is a critical component of web development. It is a programming interface for HTML and XML documents and provides a structured representation of the document in the form of a tree. This means that each HTML tag is transformed into an object which we can then manipulate using a scripting language, such as JavaScript.
The DOM is often described as the heart of web scripting languages because it has the ability to change the document structure, style, and content. When a webpage is loaded, web browsers create the DOM automatically, allowing developers to manipulate the contents of the page dynamically.
In the DOM, the document is represented as nodes and objects, constituting a structure known as the "DOM tree". This tree-like structure allows programming languages to access and manipulate each object in the document. The objects can be added, modified, or deleted.
In the context of JavaScript, whenever you interact with an element on a webpage, you're engaging with the DOM. JavaScript has the ability to add, change, and delete all the HTML elements and attributes in the page. It can also alter all the CSS styles in the page and react to all existing events on the page.
Elements of DOM
We will explore the essential components of the DOM - Nodes, Elements, and Attributes.
-
Nodes
In the DOM, everything is a node. The entire document is a document node, each HTML tag is an element node, the text inside HTML elements are text nodes, and even the comments are comment nodes. -
Elements
Elements are a type of node; they are defined by a start tag, may include text, other elements, or both, and end with an end tag. For example, in<p>Hello, World!</p>
,<p>
is the start tag,Hello, World!
is the text represented as a text node, and</p>
is the end tag. The entire line represents an element node. -
Attributes
Attributes provide additional information about an element. They are always specified in the start tag and usually come in name/value pairs likename="value"
. For example, in<a href="http://example.com">This is a link</a>
,href="http://example.com"
is an attribute of the<a>
element node.
Traversing the DOM
DOM traversal is a fundamental aspect of using JavaScript to manipulate web pages. Traversal involves moving across the DOM tree, which includes moving up (to the parent node), down (to child nodes), and sideways (to sibling nodes) from the current node.
Parent, Child, and Sibling Nodes
Every node in the DOM tree has a parent, except for the root node. Nodes may have multiple child nodes, and nodes with the same parent are called sibling nodes.
parentNode
: This property allows access to the parent node of a specified node.childNodes
: This property returns a collection of child nodes of the specified node.nextSibling
andpreviousSibling
: These properties allow access to the next and previous sibling nodes of the specified node, respectively.
Nodelist and HTMLCollection
Several methods for retrieving DOM elements, such as getElementsByClassName
or getElementsByTagName
, return multiple elements. These elements are returned as a NodeList or HTMLCollection. These are array-like collections of nodes, but are not true arrays. However, they can be looped over using a for loop, or converted into an array for more complex manipulations.
Manipulating DOM
Manipulating the DOM involves changing the content, structure, or style of HTML elements.
Creating Elements
JavaScript allows us to dynamically create elements and add them to our webpage. This is done through methods such as createElement(tagName)
, which creates a new element of the type specified by the tagName parameter, and createTextNode(data)
, which creates a new text node containing the data specified.
Updating Elements
We can change the content of an HTML element by altering the textContent
or innerHTML
properties of the element. We can also change an element's attributes using the setAttribute(name, value)
method, where name
is the name of the attribute and value
is the new value for the attribute.
Removing Elements
Elements can be removed from the DOM by calling the removeChild(child)
method on the parent of the element to be removed, or by directly calling remove()
on the element itself.
Events in DOM
Events are at the heart of interactive web applications. In the DOM, an event is a signal that something has happened. All DOM nodes can generate events, and JavaScript can react to these events through the use of Event Listeners.
Event types
There are numerous types of events that can occur while interacting with a webpage. Some common ones include:
click
: Fires when a mouse click is detected.mouseover
: Fires when the cursor moves over an element.mouseout
: Fires when the cursor moves out of an element.keydown
: Fires when a key is pressed down.load
: Fires when a page has fully loaded.
Event listeners
Event listeners are functions that wait for a certain event to occur and then execute. JavaScript provides addEventListener(type, listener)
method that attaches an event listener to an element.
Event propagation: Bubbling and Capturing
Event propagation is the process by which an event propagates or travels through the DOM tree. It occurs in two phases:
- Capturing phase: The event moves down the DOM tree, from the document object to the target element.
- Bubbling phase: The event bubbles up from the target element to the document object.
You can control the phase in which the listener function should be executed by setting the useCapture
parameter in addEventListener()
.
Modern DOM API
With the evolution of JavaScript and the DOM, new, more efficient ways to interact with the DOM have emerged. These methods are simpler and more powerful, making DOM manipulation a smoother experience.
QuerySelector and QuerySelectorAll
The querySelector()
method allows you to find the first element that matches a specified group of selectors. querySelectorAll()
returns all elements in the document that match a specified group of selectors as a static NodeList.
let el = document.querySelector(".my-class"); // gets first element with "my-class" class
let els = document.querySelectorAll(".my-class"); // gets all elements with "my-class" class
Fetch and Promises
The Fetch API makes it easier to make web requests and handle responses than with the older XMLHttpRequest
. It's built on promises, which represent a future value - a value that may not have loaded yet but will eventually.
The fetch()
method returns a promise that resolves to the Response object representing the response to the request. This promise can be used with .then()
to handle the response when it's ready.
fetch('https://api.example.com/data')
.then(response => response.json()) // parses the response as JSON
.then(data => console.log(data)) // logs the data
.catch(error => console.error('Error:', error)); // catches any error
References