Table of contents
1.
Introduction
2.
Why is DOM required?
3.
Structure of DOM
4.
Properties of DOM
5.
Examples
5.1.
1. Changing the content of an element
5.2.
2. Toggling a CSS class on an element
5.3.
3. Creating and appending new elements
5.4.
4. Removing elements from the DOM
6.
Levels of DOM
7.
Accessing the DOM
7.1.
1. Accessing elements by ID
7.2.
2. Accessing elements by class name
7.3.
3. Accessing elements by tag name
7.4.
4. Accessing elements using CSS selectors
7.5.
5. Accessing elements using XPath
8.
Frequently Asked Questions
8.1.
What is the difference between the `innerText` & `innerHTML` properties?
8.2.
How do you create & append a new element to the DOM?
8.3.
What is the purpose of the `addEventListener()` method?
9.
Conclusion
Last Updated: Oct 23, 2024
Easy

Document Object Model in Javascript

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Document Object Model, or DOM, is a fundamental concept in web development. It's a programming interface for HTML & XML documents that represents the structure of a document as a tree-like hierarchy. The DOM allows developers to access, modify, & interact with the elements & content of a web page using JavaScript. By manipulating the DOM, developers can create dynamic & interactive web experiences. 

Document Object Model in Javascript

In this article, we'll discuss the DOM in detail, like its structure, properties, methods, & interfaces. We'll also look at examples to show how the DOM can be used to build engaging web applications.

Why is DOM required?

The Document Object Model (DOM) is essential for creating interactive & dynamic web pages. Without the DOM, web pages would be static & unable to respond to user actions or update content dynamically. SOme important reasons why the DOM is required, are:

1. Interactivity: The DOM allows developers to add interactivity to web pages by enabling them to manipulate page elements in response to user events such as clicks, keystrokes, & form submissions. This makes web pages more engaging & user-friendly.
 

2. Dynamic updates: With the DOM, developers can change the content, structure, and style of a web page on the fly without requiring a page refresh. This enables features like real-time updates, live search results, and smooth page transitions.
 

3. Accessibility: The DOM provides a standardized way to access & manipulate web page elements, making it easier to create accessible web pages that can be navigated using assistive technologies like screen readers.
 

4. Separation of concerns: By using the DOM to manipulate page content, developers can separate the structure (HTML), presentation (CSS), & behavior (JavaScript) of a web page, making the code more modular, maintainable, & reusable.
 

5. Cross-platform compatibility: The DOM is a standard interface supported by all modern web browsers, ensuring that web pages built using the DOM will work consistently across different platforms and devices.

Structure of DOM

The Document Object Model represents an HTML or XML document as a tree-like structure, with each element, attribute, & piece of text in the document represented as a node in the tree. This hierarchical structure allows developers to navigate & manipulate the document easily. The main components of the DOM tree are:

1. Document node: The root node of the DOM tree, representing the entire document.
 

2. Element nodes: These nodes represent the HTML tags in the document, such as <div>, <p>, & <a>. Each element node can have child nodes, including other elements, text nodes, or attribute nodes.
 

3. Text nodes: These nodes contain the actual text content within an element. They are always leaf nodes, meaning they cannot have child nodes.
 

4. Attribute nodes: These nodes represent the attributes of an element, such as class, id, or src. They are not considered part of the main DOM tree, but are accessible through their parent element node.
 

5. Comment nodes: These nodes represent HTML comments in the document, such as <!-- This is a comment -->.


Let’s look at a simple example of an HTML document & its corresponding DOM tree structure:

<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Welcome</h1>
    <p>This is a paragraph.</p>
  </body>
</html>


Output

Output

The DOM tree for this document would look like:

- Document

  - html

    - head

      - title

        - text: "My Page"

    - body

      - h1

        - text: "Welcome"

      - p

        - text: "This is a paragraph."

Properties of DOM

The Document Object Model provides a wide range of properties that allow developers to access & manipulate various aspects of a web page. Some of the most commonly used DOM properties are:
 

1. `document.getElementById(id)`: Returns the element with the specified ID.
 

2. `document.getElementsByClassName(className)`: Returns a collection of elements with the specified class name.
 

3. `document.getElementsByTagName(tagName)`: Returns a collection of elements with the specified tag name.
 

4. `document.querySelector(selector)`: Returns the first element that matches the specified CSS selector.
 

5. `document.querySelectorAll(selector)`: Returns a collection of all elements that match the specified CSS selector.
 

6. `element.innerText`: Gets or sets the text content of an element, excluding any child elements.
 

7. `element.innerHTML`: Gets or sets the HTML content within an element, including any child elements.
 

8. `element.getAttribute(name)`: Returns the value of the specified attribute on an element.
 

9. `element.setAttribute(name, value)`: Sets the value of the specified attribute on an element.
 

10. `element.style` allows developers to access and modify an element's inline styles.

Examples

Let's take a look at some practical examples of how to use the DOM to manipulate web page content and create interactive experiences.

1. Changing the content of an element


HTML:

<p id="myParagraph">This is the original text.</p>


Javascript:

const myParagraph = document.getElementById('myParagraph');
myParagraph.innerText = 'This is the new text.';

2. Toggling a CSS class on an element


HTML: 

<div id="myDiv">Click me to toggle the class!</div>


CSS : 

.highlighted {
  background-color: yellow;
  font-weight: bold;
}


Javascript:

const myDiv = document.getElementById('myDiv');

myDiv.addEventListener('click', function() {
  myDiv.classList.toggle('highlighted');
});

3. Creating and appending new elements

HtML: 

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>


Javascript:

const myList = document.getElementById('myList');


const newItem = document.createElement('li');
newItem.innerText = 'Item 3';
myList.appendChild(newItem);

4. Removing elements from the DOM

Html: 

<div id="myDiv">
  <p class="myClass">Paragraph 1</p>
  <p class="myClass">Paragraph 2</p>
  <p class="myClass">Paragraph 3</p>
</div>


Javascript:

const myDiv = document.getElementById('myDiv');
const myParagraphs = myDiv.getElementsByClassName('myClass');


while (myParagraphs.length > 0) {
  myDiv.removeChild(myParagraphs[0]);
}

Levels of DOM

The Document Object Model (DOM) has evolved over time, with different levels representing the added features and improvements in each iteration. The levels of DOM are:
 

1. DOM Level 0: This level represents the early, unofficial DOM implementation that existed before the standardization of the DOM by the World Wide Web Consortium (W3C). It included basic methods like `document.images`, `document.forms`, and `document.layers`.
 

2. DOM Level 1: Released in 1998, this level introduced the official W3C standardization of the DOM. It provided a complete model for the HTML and XML documents, including methods for accessing and manipulating document elements and their attributes.
 

3. DOM Level 2: Published in 2000, DOM Level 2 added more functionality to the previous level. It introduced the concept of "namespace support" and added new modules such as "DOM Events," "DOM Style," and "DOM Traversal and Range." These modules provided a standardized way to handle events and work with CSS styles.
 

4. DOM Level 3: Released in 2004, this level further extended the DOM with new modules and features. It introduced the "DOM Load and Save" module for parsing XML documents, the "DOM Validation" module for document validation against a schema, and enhancements to the existing modules.
 

5. DOM Level 4: This level is currently a work in progress, with some features already implemented in modern browsers. It aims to improve the DOM by adding new methods and properties to enhance performance and address issues from previous levels.
 

It's important to note that most modern web browsers support DOM Level 3 and many features from DOM Level 4. When working with the DOM, developers should be aware of the browser compatibility of the features they use to ensure a consistent experience across different platforms.

Accessing the DOM

To work with the DOM, developers need to access the elements and attributes of a web page. There are several ways to access the DOM, depending on the specific needs of the project. Some common methods are:

1. Accessing elements by ID

Javascript

const element = document.getElementById('elementId');


This method returns the element with the specified ID, or `null` if no element is found.

2. Accessing elements by class name

Javascript: 

const elements = document.getElementsByClassName('className');


This method returns a live `HTMLCollection` of all elements with the specified class name.

3. Accessing elements by tag name


Javascript

const elements = document.getElementsByTagName('tagName');


This method returns a live `HTMLCollection` of all elements with the specified tag name.

4. Accessing elements using CSS selectors


Javascript : 

const element = document.querySelector('cssSelector');
const elements = document.querySelectorAll('cssSelector');


`querySelector()` returns the first element that matches the specified CSS selector, while `querySelectorAll()` returns a static `NodeList` of all matching elements.

5. Accessing elements using XPath

Javascript: 

const elements = document.evaluate('xpathExpression', document, null, XPathResult.ANY_TYPE, null);


This method uses an XPath expression to locate elements in the document. It returns an `XPathResult` object, which can be iterated to access the matching elements.


Once you have accessed an element, you can use the properties & methods of the DOM to manipulate its content, attributes, & styles, as well as traverse the DOM tree to access related elements.


Let’s see an example that shows accessing elements using different methods:


HTML: 

<div id="myDiv">
  <p class="myClass">Paragraph 1</p>
  <p class="myClass">Paragraph 2</p>
  <span>Span 1</span>
</div>


Javascript: 

const myDiv = document.getElementById('myDiv');
const myParagraphs = document.getElementsByClassName('myClass');
const mySpans = myDiv.getElementsByTagName('span');
const firstParagraph = document.querySelector('#myDiv .myClass');

Frequently Asked Questions

What is the difference between the `innerText` & `innerHTML` properties?

`innerText` returns the visible text content of an element, while `innerHTML` returns the HTML content, including any child elements.

How do you create & append a new element to the DOM?

To create a new element, use `document.createElement()`. To append it to an existing element, use the `appendChild()` method on the parent element.

What is the purpose of the `addEventListener()` method?

`addEventListener()` is used to attach an event handler to an element, allowing you to execute JavaScript code when a specific event (e.g., click, keypress) occurs on that element.

Conclusion

In this article, we have learned about the Document Object Model (DOM), a powerful API for interacting with HTML & XML documents. We discussed the structure of the DOM, its properties, methods, & interfaces, & saw practical examples of how to manipulate web page content using JavaScript. With DOM, developers can create dynamic, interactive web experiences that engage users & bring web pages to life. 

You can also check out our other blogs on Code360.

Live masterclass