“`html
The Document Object Model (DOM) serves as a mechanism that enables JavaScript to engage with the contents of a webpage. It facilitates modifications, additions, or deletions of elements such as text, images, and links. Think of it as a channel linking the HTML layout of a webpage to the JavaScript code executed on it. In this post, we’ll explore how you can utilize the DOM to enhance your site.
Table of Contents:
- What is the DOM?
- How Is DOM Connected to JavaScript?
- Grasping the DOM Structure
- Manipulating the DOM Using JavaScript
- Event Management in the DOM
- DOM Navigation
- Optimal Practices for DOM Manipulation
- Final Thoughts
What is the DOM?
The DOM (Document Object Model) is a programming interface for web documents. It visualizes the layout of a webpage as a tree of objects, where each component, such as text, images, or links, is an object that can be altered or updated. This enables you to refresh the webpage content without requiring a complete reload.
How Is DOM Connected to JavaScript?
JavaScript and the DOM collaborate to enhance user interactivity on web pages. The DOM plays a crucial role in web development. Let’s delve into its contributions:
- Modifies web pages via the DOM: By utilizing the DOM, you can swiftly update text, images, and other elements on the page without needing to reload the entire page.
- Enhances interactivity on web pages: The DOM permits JavaScript to react to user inputs, such as clicking buttons or completing forms, fostering a more interactive experience.
- Access and modify page components: JavaScript leverages the DOM to locate elements on the page, like headings or images, and then perform modifications, such as changing text or colors.
Grasping the DOM Structure
The DOM symbolizes the composition of a webpage like a tree, where various elements resemble branches. Let’s explore how the DOM is arranged:
1. DOM Tree Organization
The DOM framework resembles a tree, with the root node positioned at the top, and everything else, such as images, paragraphs, and links, connected underneath like branches. This tree formation makes it straightforward to organize and locate different sections of the webpage.
2. Nodes, Elements, and Attributes
- Nodes: Within the DOM, everything is referred to as a “node.” There are three primary categories of nodes:
- Element Nodes: These correspond to HTML tags, such as <p> or <div>.
- Text Nodes: These represent the actual text or words encapsulated within the HTML tags.
- Attribute Nodes: These are additional details found within HTML tags, such as id=”header” or class=”main”.
- Elements: Elements encompass the HTML tags (like <h1>, <p>, and <img>). These elements can be modified through JavaScript.
- Attributes: Attributes provide supplementary information about elements. For example, the src attribute in an <img> tag indicates where the browser can locate the image.
3. The Root Node and Child Nodes
- Root Node: The root node signifies the starting point of the DOM tree, typically the <html> tag in an HTML page, with all other components linked to it.
- Child Nodes: These represent the smaller elements of the webpage that branch from the root node. For instance, the <head> and <body> tags are considered child nodes of the <html> tag. Elements such as <p> or <img> within the <body> also count as child nodes.
A Basic Example of the DOM Tree

Manipulating the DOM Using JavaScript
Having understood the DOM structure, let’s examine how you can access, modify, create, insert, and delete elements in the DOM utilizing JavaScript.
Accessing DOM Components
To alter something on a webpage, the initial step is to “locate” the specific item you wish to modify. The following methods will assist you in this process.
1. getElementById(): This method enables you to find an element using its ID, which acts as a unique identifier for an element.
Syntax:
let element = document.getElementById(‘myId’);
2.
“““html
getElementsByClassName(): This function will assist you in locating all elements sharing the same class.
Syntax:
let elements = document.getElementsByClassName(‘myClass’);
3. querySelector(): This is a highly adaptable approach to select elements via CSS-style selectors, such as ID, class, or tag.
Syntax:
let element = document.querySelector(‘.myClass’);
4. querySelectorAll(): This operates similarly to querySelector(), but it retrieves all elements that correspond to the selector.
Syntax:
let elements = document.querySelectorAll(‘.myClass’);
Changing DOM Elements
After identifying the element you wish to modify, you can alter it in various manners.
1. Modifying text content: You can adjust the content within an element, such as text or a heading, by utilizing innerText.
Syntax:
let element = document.getElementById(‘myId’);
element.innerText = ‘Updated text here!’;
2. Changing attributes: You can modify attributes like links or images through the setAttribute() method.
Syntax:
let link = document.getElementById(‘myLink’);
link.setAttribute(‘href’, ‘https://www.newurl.com’);
3. Adding/Removing HTML elements: You have the ability to insert new elements such as a new paragraph or remove existing ones.
Syntax (To insert a new element):
let newElement = document.createElement(‘p’);
newElement.innerText = ‘I am a new paragraph!’;
document.body.appendChild(newElement);
Syntax (To eliminate an element):
let elementToRemove = document.getElementById(‘removeMe’);
document.body.removeChild(elementToRemove);
Inserting and Deleting Elements
You can decide where the new elements will be situated, ensuring they are inserted appropriately.
1. appendChild(): This adds a new element at the conclusion of an existing element.
Syntax:
let newItem = document.createElement(‘li’);
newItem.innerText = ‘New list item’;
let list = document.getElementById(‘myList’);
list.appendChild(newItem);
2. removeChild(): This eliminates an existing element from the document.
Syntax:
let itemToRemove = document.getElementById(‘itemToRemove’);
let list = document.getElementById(‘myList’);
list.removeChild(itemToRemove);
3. insertBefore(): This allows you to insert a new element before an existing one.
Syntax:
let newItem = document.createElement(‘li’);
newItem.innerText = ‘This comes before another item’;
let list = document.getElementById(‘myList’);
let firstItem = document.getElementById(‘firstItem’);
list.insertBefore(newItem, firstItem);
Example:
Let’s examine an instance utilizing the methods discussed above:
DOM Manipulation Example Initial Heading
This is a description.
- First item
// Accessing elements
let header = document.getElementById(‘header’);
let description = document.querySelector(‘.description’);
// Modifying text content
header.innerText = ‘Updated Heading’;
description.innerText = ‘This description has been updated!’;
// Inserting a new element
let newItem = document.createElement(‘li’);
newItem.innerText = ‘New list item’;
document.getElementById(‘myList’).appendChild(newItem);
// Add a new item when the button is clicked
document.getElementById(‘addItemBtn’).addEventListener(‘click’, function() {
let newItem = document.createElement(‘li’);
newItem.innerText = ‘Another new item’;
document.getElementById(‘myList’).appendChild(newItem);
});
Output:

In this case,
- The heading updates to “Updated Heading“.
- The description paragraph is refreshed with new text.
- A new list item is appended to the list automatically when the page is loaded.
- Each time the Add List Item button is pressed, a new list item is incorporated into the document.
Event Handling in the DOM
Event handling enables you to add interactivity to a webpage, such as clicking buttons and pressing keys. Let’s review the main concepts of event handling.
Comprehending DOM Events
DOM events are occurrences that take place within a web page. These occurrences encompass:
- Clicking a button
- Typing on the keyboard
- Hovering the mouse over an element
When such an action occurs, the browser generates an event that can be responded to using JavaScript.
Event Listeners and Handlers
In JavaScript, event listeners and event handlers are utilized to manage user actions on the web page, such as pressing buttons, hitting keys, etc.
1. addEventListener()
addEventListener() serves as a method to ‘listen’ for events, like button clicks and others. This function helps you execute a task when an event occurs.
Example: If you aim to display a message when a button is clicked.
let button = document.getElementById('myButton'); button.addEventListener('click', function() { // Display an alert when the button is pressed alert('Button clicked!'); });
Output:

2. Event Propagation: Capturing vs Bubbling
An event behaves in a couple of manners when it occurs:
- Bubbling: The event starts at the element, like the button, and ascends to parent elements, such as a div.
- Capturing: The event begins from the outermost element, like the document, and descends toward the specific element, like the button.
Note: By default, most events utilize bubbling, but you can modify this if necessary.
“““html
Frequently Encountered Events
Below are several frequently encountered events you may utilize:
- click: This occurs when you press on an element.
- keyup: This takes place when you let go of a key on the keyboard.
- keydown: This happens when you press a key down.
- mouseover: This occurs when the mouse is over an element.
Event Propagation
Event Propagation is a strategy in which you can attach a single event listener to a parent element, allowing it to manage events for its child elements. This can be accomplished through event bubbling, where events ascend through the DOM from child elements to their ancestors.
Illustration:
Event Propagation
- Item 1
- Item 2
- Item 3
Result:

In this instance,
- The click event is linked to the parent ul.
- When a child li is selected, the event ascends to the parent, and the listener verifies if the target is a li possessing the class item.
DOM Navigation
DOM navigation refers to moving through the HTML framework of the document to locate and manipulate elements such as text and tags. JavaScript provides an array of tools to traverse through the structure and access various portions of the page.
Navigating Through DOM Nodes
All items are nodes in the DOM tree. There are various categories of nodes:
- Element nodes: These signify HTML tags (like <div>, <p>, etc.).
- Text nodes: These house the text within HTML elements.
- Attribute nodes: These indicate the attributes of elements (such as id, class, etc.).
Navigating through DOM nodes involves accessing parent, child, and sibling nodes to traverse the DOM structure.
Techniques for Navigating the DOM
Here are the primary techniques that assist you in moving through the DOM:
1. parentNode: The parentNode property assists you in locating the parent element of the current element.
Syntax:
let element = document.getElementById(‘childElement’);
let parent = element.parentNode;
console.log(parent);
2. childNodes: The childNodes property provides all the child nodes of an element, which comprises text nodes like spaces and newlines, along with comment nodes.
Syntax:
let parent = document.getElementById(‘parentElement’);
let children = parent.childNodes;
console.log(children);
3. nextSibling: The nextSibling property helps you find the subsequent sibling node, which is the next node that follows the current one.
Syntax:
let currentNode = document.getElementById(‘currentElement’);
let next = currentNode.nextSibling;
console.log(next);
4. previousSibling: The previousSibling property assists you in identifying the preceding sibling node, which is the node immediately before the current one.
Syntax:
let currentNode = document.getElementById(‘currentElement’);
let previous = currentNode.previousSibling;
console.log(previous);
Efficient DOM Tree Navigation
When navigating the DOM, always opt for the appropriate method to locate what you need. For instance, if you desire only the child elements excluding text or comments, use children instead of childNodes. Similarly, if you wish to locate the next or previous element rather than text, employ nextElementSibling or previousElementSibling.
Illustration:
DOM Navigation // Select an element (in this case, the first paragraph) let firstParagraph = document.querySelector('p'); // parentNode let parent = firstParagraph.parentNode; console.log("Parent of first paragraph:", parent); // childNodes (all nodes including text and comment nodes) let childNodes = parent.childNodes; console.log("Child nodes of parent (including text and comments):", childNodes); // children (only element nodes) let children = parent.children; console.log("Element children of parent:", children); // nextSibling let nextSibling = firstParagraph.nextSibling; console.log("Next sibling (can be text or element):", nextSibling); // previousSibling let previousSibling = firstParagraph.previousSibling; console.log("Previous sibling (can be text or element):", previousSibling); // firstElementChild let firstChild = parent.firstElementChild; console.log("First child element of parent:", firstChild); // lastElementChild let lastChild = parent.lastElementChild; console.log("Last child element of parent:", lastChild);Paragraph 1
Paragraph 2
Paragraph 3
Nested Paragraph
Result:

Optimal Practices for DOM Manipulation
While engaging with JavaScript DOM manipulation, numerous optimal practices can aid you in evading common pitfalls, structuring your code, and enhancing performance. Let’s explore these in detail.
“““html
detail:
Averting Frequent Errors
- Avoid altering the DOM too frequently: Modifying the DOM excessively may lead to performance slowdowns. Instead, consider batch processing your alterations and applying them simultaneously.
- Do not repeatedly query the DOM: Continuously searching for elements can be inefficient. Store references to elements that you frequently interact with.
- Refrain from using innerHTML: Utilizing innerHTML can lead to inefficiencies and security risks. Opt for safer and more efficient alternatives like altering text content or creating elements directly.
Structuring Your Code for Effective DOM Access
- Implement event delegation: Rather than attaching event listeners to each individual element, you can assign a single listener to a parent element. This approach is more efficient when dealing with a large number of items.
- Divide your code into components: Segment your code into smaller, reusable sections that perform specific functions. This will enhance the organization of your code.
Enhancing Performance
- Utilize requestAnimationFrame for animations: This technique allows you to create more fluid animations by aligning them with the browser’s rendering cycle.
- Avoid frequently changing layout properties: Modifying properties such as width and height multiple times may lead to performance issues. Prefer properties like transform or opacity, which are more efficient.
- Employ classList for class manipulation: Use classList to add, remove, or toggle CSS classes instead of altering the entire className, which may overwrite other classes.
- Optimize for text changes: When you merely need to modify text, methods like textContent are preferable to innerHTML for enhanced performance.
- Manage events effectively: For events that occur frequently, such as scrolling or resizing, techniques like debouncing can help reduce the number of invocations, thereby boosting performance.
Final Thoughts
In this article, we have explored how to utilize the DOM to enhance your website. The Document Object Model (DOM) serves as a conduit for JavaScript to engage with a webpage’s content. It acts as a link between the HTML architecture of a webpage and the JavaScript code operating within it.
Frequently Asked Questions
The post JavaScript HTML DOM first appeared on Intellipaat Blog.
“`