DEV Community

Tamilselvan K
Tamilselvan K

Posted on • Edited on

Day-20 DOM Basics: Select, Update, Create, and Remove Elements Using JavaScript

The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

Image description

Let me break down the key actions I learned: Select, Update, Create, and Remove elements from the DOM.


1. Selecting Elements

To manipulate anything in the DOM, first we need to select it. Here are some common methods:

document.getElementById("myId");            // Select by ID
document.getElementsByClassName("myClass"); // Select by class (HTMLCollection)
document.getElementsByTagName("div");       // Select by tag name
document.querySelector(".myClass");         // Select first match[TBD]
document.querySelectorAll("p");             // Select all matching[TBD]

Enter fullscreen mode Exit fullscreen mode

Example:

let heading = document.getElementById("main-heading");
Enter fullscreen mode Exit fullscreen mode

2. Updating Elements

Once selected, we can update their content or style:

let title = document.getElementById("id name");
title.textContent = "Welcome to my site!";
title.style.color = "blue";
Enter fullscreen mode Exit fullscreen mode

Example:

document.getElementById("id name").innerHTML = "This is a new paragraph text!";
Enter fullscreen mode Exit fullscreen mode

3. Creating Elements

We can dynamically create elements and add them to the page:

let newElement = document.createElement("div");
newElement.textContent = "I was created using JS!";
document.getElementById("id name").appendChild(newElement);
Enter fullscreen mode Exit fullscreen mode

You can also set attributes:[TBD]

newElement.setAttribute("class", "new-class");
Enter fullscreen mode Exit fullscreen mode

4. Removing Elements

Finally, we can remove elements from the DOM:

let elementToRemove = document.getElementById("id name");
elementToRemove.remove();
Enter fullscreen mode Exit fullscreen mode

Or using the parent element:[TBD]

let parent = document.getElementById("container");
let child = document.getElementById("item");
parent.removeChild(child);
Enter fullscreen mode Exit fullscreen mode

Summary

Action Method
Select getElementById, querySelector
Update textContent, innerHTML, style
Create createElement, appendChild
Remove remove(), removeChild()

Final Thoughts

Learning the DOM opened up a whole new level of interaction with web pages. It's like learning how to control every part of a website from JavaScript. I'm excited to use these techniques in my future projects!

Reference:
I refer the above information from ChatGPT and W3SCHOOLS


Top comments (0)