Learn the concept
DOM
Use querySelector/querySelectorAll (CSS selectors) or getElementById to select elements. Manipulate them via textContent, innerHTML, classList, style, setAttribute, and createElement/appendChild for creating new elements.
The DOM (Document Object Model) is a tree representation of the HTML document that JavaScript can interact with.
Selecting elements:
document.querySelector(selector) — first match (CSS selector)document.querySelectorAll(selector) — all matches (NodeList)document.getElementById(id) — by IDdocument.getElementsByClassName(class) — by class (live collection)Modifying content:
element.textContent — get/set text (safe, no HTML parsing)element.innerHTML — get/set HTML (avoid with user input — XSS risk)Modifying attributes and classes:
element.classList.add/remove/toggle/containselement.setAttribute(name, value)element.style.property = valueCreating and removing:
document.createElement(tag)parent.appendChild(child) / parent.append(child)element.remove()// Selecting
const heading = document.querySelector('h1');
const buttons = document.querySelectorAll('.btn');
const main = document.getElementById('main');
// Modifying content
heading.textContent = 'New Title';
// Classes
heading.classList.add('active');
heading.classList.toggle('hidden');
heading.classList.contains('active'); // true
// Styles
heading.style.color = 'blue';
heading.style.fontSize = '24px';
// Attributes
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
link.getAttribute('href');Displaying error messages, highlighting invalid fields, and managing form state via DOM manipulation
Adding or removing CSS classes or data attributes on the root element for dark/light mode switching
Loading and inserting content into the page from APIs without triggering full page reloads
Build a todo app using only vanilla DOM methods like createElement, classList, and textContent
Build real-time form validation with DOM feedback including error messages and input styling