DOM Manipulation in JavaScript
The DOM (Document Object Model) is the bridge between your JavaScript code and the HTML that shows up on the screen. It allows you to change text, styles, and attributes, or even add and remove elements dynamically.
π³ What is the DOM?
Imagine your HTML document as a tree. The browser converts your HTML tags into a tree of objects that JavaScript can read and change.
- Document: The root of the tree (the whole page).
- Nodes: Every part of the document (elements, text, comments) is a node.
console.log(document); // Shows the entire HTML structureπ― Selecting Elements
Before you can change an element, you need to find it.
getElementById
The fastest way to select an element if it has an ID.
<h1 id="title">Hello World</h1>const title = document.getElementById('title');querySelector
Selects the first element that matches a CSS selector (like class, ID, or tag).
const btn = document.querySelector('.btn'); // Selects first element with class "btn"const header = document.querySelector('header h1'); // Selects h1 inside headerquerySelectorAll
Selects all elements that match. Returns a NodeList (similar to an array).
const items = document.querySelectorAll('li');items.forEach(item => { console.log(item.textContent);});βοΈ Changing Content
Once you have an element, you can change whatβs inside it.
textContent
Gets or sets the text content. It ignores HTML tags.
const title = document.querySelector('h1');title.textContent = "Welcome to JavaScript!";innerHTML
Gets or sets the HTML inside an element. Be careful with this oneβit can be a security risk if you use it with user input (XSS attacks).
const container = document.querySelector('.container');container.innerHTML = "<p>This is a <strong>new</strong> paragraph.</p>";π¨ Changing Styles
You can change CSS styles directly using the style property.
const box = document.querySelector('.box');
box.style.backgroundColor = 'blue';box.style.color = 'white';box.style.fontSize = '20px';[!NOTE] CSS properties in JavaScript use camelCase. So
background-colorbecomesbackgroundColor.
Better Way: classList
Instead of changing styles one by one, itβs often cleaner to add or remove CSS classes.
box.classList.add('active'); // Add a classbox.classList.remove('active'); // Remove a classbox.classList.toggle('active'); // Add if missing, remove if presentποΈ Creating and Adding Elements
You can build new parts of the page from scratch.
// 1. Create the elementconst newBtn = document.createElement('button');
// 2. adding styles and contentnewBtn.textContent = "Click Me";newBtn.classList.add('primary-btn');
// 3. Add it to the pageconst container = document.querySelector('.container');container.appendChild(newBtn); // Adds to the end of the containerRemoving Elements
const oldItem = document.querySelector('.old-item');oldItem.remove();π Interactive Example
Letβs make a simple βTo-Doβ adder.
HTML:
<input type="text" id="input" placeholder="Enter task..."><button id="addBtn">Add</button><ul id="list"></ul>JavaScript:
const input = document.getElementById('input');const btn = document.getElementById('addBtn');const list = document.getElementById('list');
btn.addEventListener('click', function() { const text = input.value;
if (text !== "") { // Create new list item const li = document.createElement('li'); li.textContent = text;
// Add to list list.appendChild(li);
// Clear input input.value = ""; }});β Best Practices
- Cache selections: If you use an element more than once, save it in a variable.
- Use
classList: Prefer toggling classes over changingstyledirectly for complex changes. - Minimize layout thrashing: extensive DOM changes can slow down the page. Try to make changes in batches.
Happy Coding!