An Introduction to JavaScript: DOM Manipulation
An Introduction to JavaScript: DOM Manipulation

An Introduction to JavaScript: DOM Manipulation

The Document Object Model (DOM) serves as a pivotal programming interface for web document manipulation. It functions as an Application Programming Interface (API), facilitating developers' efficient interaction with and alteration of HTML documents. This article delves into the fundamental concepts of the DOM, drawing insights from various sources.


What is a Domain Object Model (DOM)?

The DOM represents a web page as a structured hierarchy of nodes and objects. This hierarchical representation empowers programs to dynamically modify not just the structure but also the style and content of a web document. It acts as an object-oriented model of a web page, rendering it amenable to manipulation via scripting languages such as JavaScript.

The DOM visualizes an HTML document as a tree of nodes, granting developers a potent toolkit of functions for executing tasks like addition, removal, and modification of different document components. These actions can be executed across diverse platforms and programming languages, underlining the DOM's cross-platform and language-independent nature.


Why is the DOM important?

The significance of the DOM lies in its capacity to bridge the divide between web documents and programming languages. It enables developers to craft dynamic and interactive web pages by offering a structured means of accessing and altering content. This proves particularly invaluable in modern web development, where user interactions and real-time updates are paramount.


Working with the DOM

Developers frequently employ languages like JavaScript to work with the DOM. By leveraging the DOM's methods and properties, they can pinpoint specific elements within a web page, modify their attributes, and even respond to user interactions. This dynamic functionality is what imbues modern web applications with responsiveness and engagement.

Here is a code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM learning with DevHacks</title>
    <link rel="stylesheet" href="style.css">
</head>
<body  class="dark-mode">
    <div>
        <h1 class="heading">DOM learning in the easy way</h1>
        <p id="sample">Lorem ipsum dolor sit amet.</p>
    </div>
    <script type="text/javascript" src="dom.js"></script>
</body>
</html>        

And the DOM tree is


DOM tree sample

Node Types:

There exist two primary node types within the DOM:

  • Root node
  • Child node

In the diagram above, the 'document' serves as the root node, with the nodes below it designated as child nodes.

Accessing the DOM

Here are the essential steps for accessing and working with the DOM:

  • Select Element

document.getElementById(id)        
document.querySelector(selector)        
document.querySelectorAll(selector)        

  • Manipulate ElementWhen you have selected any element, you can manipulate them in various ways:

  1. Changing content: You can change the text or HTML content of the element.
  2. Modifying attributes: You can change attributes like ‘src’, ‘href’, ‘class’, etc.
  3. Adding or removing elements: You can add new elements or remove existing ones from the DOM.
  4. Handling events: You can attach event listeners to respond to user interactions.

  • Practical implementationHere is the previous code that I have shared but I have provided the id of the ‘p’ tag “sample”.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM learning with DevHacks</title>
    <link rel="stylesheet" href="style.css">
</head>
<body  class="dark-mode">
    <div>
        <h1 class="heading">DOM learning in the easy way</h1>
        <p id="sample">Lorem ipsum dolor sit amet.</p>
    </div>
    <script type="text/javascript" src="dom.js"></script>
</body>
</html>        

And its output is


Output

Now I am changing the text of the paragraph by using JavaScript code.

// Get the paragraph element by its ID
const paragraphElement = document.getElementById("sample");

// Change the text content of the paragraph
paragraphElement.textContent = "Updated text using DOM manipulation";        

Now check the output on the browser.

Output

  • Wait for DOM ready It is necessary that the DOM should be fully loaded to manipulate it. There is a way to do it by using an event listener that listens to the “DOMContentLoaded” event. This ensures that the scripts run when the DOM is ready for the manipulation.

document.addEventListener("DOMContentLoaded", function() {
    // Add a new element after the paragraph
    const newElement = document.createElement("p");
    newElement.textContent = "This is a new paragraph.";

    // Append the new element to the div
    const divElement = document.querySelector("div");
    divElement.appendChild(newElement);
})        

Now the output would be

document.addEventListener("DOMContentLoaded", function() {
    // Add a new element after the paragraph
    const newElement = document.createElement("p");
    newElement.textContent = "This is a new paragraph.";

    // Append the new element to the div
    const divElement = document.querySelector("div");
    divElement.appendChild(newElement);
})        

  • Accessing Nested ElementsYou can also access nested elements by navigating through the DOM tree. Here is a practical example:

<!-- Second Div -->
<div id="container">
    <p class="nested">Nested Element in DevHacks</p>
 </div>        

Now you can access like this

const containerDiv = document.getElementById("container");
const nestedElement = containerDiv.querySelector(".nested");        

Note that these are the fundamental steps to play with the DOM in web development. Depending on specific requirements, you may need to perform complex operations.

Resources to learn JavaScript

I have found one more YouTube channel to share with you.

Chai aur Code

Other resources are shared at the end of this article.

An Introduction to JavaScript: Understanding the Fundamentals

Sehrish Lateef

Off-page Specialist| Helping SAAS / B2B Businesses | Get Leads, Traffic, and SERP Ranking with the Help of Premium Link Building

1 年

I'm really appreciative of what you did Ghufran Hasan

Kainat Fatima

I help CEOs, founders, and solopreneurs build and monetize their LinkedIn? brands to generate leads | Content, Engagement, & outreach | LinkedIn Account Manager

1 年

Commendable effort

?? "Stay in the loop with our newsletter! ?? Check it out here: https://www.dhirubhai.net/newsletters/devhacks-7091880540613550080/"

回复

要查看或添加评论,请登录

Ghufran Hasan的更多文章

社区洞察

其他会员也浏览了