Introduction to the DOM in JavaScript - CodingQue

Introduction to the DOM in JavaScript

The Document Object Model (DOM) is an essential part of web development that represents the structure of an HTML document. JavaScript can access and manipulate elements within the DOM, allowing developers to create dynamic and interactive web pages.

What is the DOM?

The DOM is a programming interface for HTML documents. It represents the document as a structured group of nodes and objects. The DOM allows JavaScript to interact with the page, meaning it can add, remove, or modify content.

The DOM Tree Structure

The DOM represents each HTML element as a node in a hierarchical tree structure. In this tree:

This structure allows JavaScript to locate and modify specific parts of the document. For example, here’s a simple HTML document structure:

<!DOCTYPE html>
<html>
    <head>
        <title>Sample Page</title>
    </head>
    <body>
        <h1>Hello World</h1>
        <p>This is a paragraph.</p>
    </body>
</html>

JavaScript and the DOM

JavaScript provides several methods to interact with the DOM, enabling developers to select and manipulate elements:

Example: Modifying a DOM Element with JavaScript

In the example below, we’ll select a heading by its ID and change its text content using JavaScript.

Original Heading

<script>
function changeHeading() {
    const heading = document.getElementById('example-heading');
    heading.textContent = 'Heading Changed with JavaScript!';
}
</script>

Explanation of the Code

Here’s how the code works:

Previous Next
Modern Footer