DOM Manipulation
What Is the DOM?
When a browser loads an HTML page, it builds a tree-like model of every element — this model is the Document Object Model (DOM). Think of it like a family tree: the <html> element is the grandparent, <body> is the parent, and all the <div>s, <p>s, and <button>s are children and grandchildren.
JavaScript can read, change, add, or remove any part of this tree. That's how interactive websites work — the HTML stays the same, but JavaScript reshapes the DOM in real time.
Selecting Elements
Changing Content, Styles & Attributes
Once you've selected an element, you can change almost anything about it:
.textContent— the plain text inside (safe, no HTML parsing).innerHTML— the HTML content (be careful — can create security issues if used with user input).style.property— change inline CSS styles.classList— add, remove, or toggle CSS classes.setAttribute()/.getAttribute()— change HTML attributes likesrc,href,disabled
Modifying Elements
Creating Elements & Handling Events
You can build new HTML elements entirely from JavaScript and insert them into the page. This is how dynamic content works — like adding a new comment, a new todo item, or a notification.
Event listeners let your code react to user actions — clicks, key presses, form submissions, mouse movements, and more. You attach a listener to an element, and JavaScript calls your function whenever that event happens.
Event delegation is a pro technique: instead of adding listeners to every child element, you add ONE listener to the parent and check which child was clicked. This is faster and works even for elements added later.