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:
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]
Example:
let heading = document.getElementById("main-heading");
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";
Example:
document.getElementById("id name").innerHTML = "This is a new paragraph text!";
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);
You can also set attributes:[TBD]
newElement.setAttribute("class", "new-class");
4. Removing Elements
Finally, we can remove elements from the DOM:
let elementToRemove = document.getElementById("id name");
elementToRemove.remove();
Or using the parent element:[TBD]
let parent = document.getElementById("container");
let child = document.getElementById("item");
parent.removeChild(child);
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)