DOM Basics

DOM Basics

The Document Object Model is the tree of HTML elements. JavaScript can query and change it.

Selecting elements

javascript
document.getElementById(\"myId\"); document.querySelector(\".my-class\"); document.querySelectorAll(\"p\");

querySelector returns the first match; querySelectorAll returns a NodeList.

Changing content and attributes

javascript
const el = document.querySelector(\"#title\"); el.textContent = \"New text\"; el.innerHTML = \"<strong>Bold</strong>\"; el.setAttribute(\"href\", \"/page\"); el.classList.add(\"active\");

Events

javascript
const btn = document.querySelector(\"button\"); btn.addEventListener(\"click\", () => { console.log(\"Clicked\"); });

Common events: click, submit, input, keydown, load. In React or Vue you typically use their event bindings instead of raw addEventListener.