DEV Community

Jeeva Aj
Jeeva Aj

Posted on

JAVASCRIPT - DOM

In JavaScript, DOM (Document Object Model) manipulation is essential for interacting with and changing HTML elements on a webpage. Here’s a simple guide to selecting, updating, creating, and removing elements using JavaScript:


📌 1. Select Elements

You can select HTML elements using several methods:

// Select by ID
let title = document.getElementById("main-title");

// Select by class
let items = document.getElementsByClassName("item");

// Select by tag
let paragraphs = document.getElementsByTagName("p");

// Modern method - querySelector (returns the first match)
let firstItem = document.querySelector(".item");

// querySelectorAll (returns all matches as a NodeList)
let allItems = document.querySelectorAll(".item");


📝 2. Update Elements

You can change text, attributes, styles, and more:

// Change text content
title.textContent = "Updated Title";

// Change inner HTML
title.innerHTML = "New HTML Content";

// Change an attribute
title.setAttribute("class", "highlighted");

// Change styles directly
title.style.color = "red";
title.style.fontSize = "24px";


🛠️ 3. Create Elements

To create a new element:

// Create a new element
let newDiv = document.createElement("div");

// Add content
newDiv.textContent = "I am a new div";

// Add class
newDiv.classList.add("new-box");

// Append to body or any other parent
document.body.appendChild(newDiv);


❌ 4. Remove Elements

To remove an existing element:

// Select the element
let unwanted = document.querySelector(".remove-me");

// Remove it from the DOM
unwanted.remove();

For older browsers:

unwanted.parentNode.removeChild(unwanted);


✅ Summary Table:

Action Method Example

Select document.querySelector("#id")
Update element.textContent = "Hello"
Create document.createElement("div")
Remove element.remove()

Thank you for reading my blog today. See ya tomorrow.

Top comments (0)