Dynamic UI
Lets you update content on the page without needing to reload it.
The DOM (Document Object Model) is the version of your HTML that lives in memory, built by the browser.
JavaScript talks to this structure to:
Dynamic UI
Lets you update content on the page without needing to reload it.
User Interaction
Lets you handle clicks, typing, and keyboard events.
Data Rendering
Lets you turn data from an API into something visible on the screen.
Real Apps
Used in things like forms, dashboards, modals (popups), and lists.
// Old waysdocument.getElementById("id");document.getElementsByClassName("class");// Modern, flexibledocument.querySelector(".card");document.querySelectorAll(".btn");getElementById
This is the fastest option, and it gives back a single element.
querySelector
This uses CSS selectors, so it is more flexible to use.
querySelectorAll
This gives back a NodeList (which is not exactly the same thing as an array).
element.textContent;element.innerText;element.innerHTML;element.textContent = "Hello";element.innerHTML = "<b>Hello</b>";element.setAttribute("id", "main");element.getAttribute("id");
element.classList.add("active");element.classList.remove("hidden");element.classList.toggle("open");const div = document.createElement("div");div.textContent = "Hello";
document.body.append(div);parent.append(child);parent.prepend(child);element.before(newNode);element.after(newNode);element.remove();parent.removeChild(child);oldEl.replaceWith(newEl);Instead of attaching a separate listener to every single element, you can attach just one listener to a parent element:
document.querySelector("#list").addEventListener("click", (e) => { if (e.target.tagName === "LI") { console.log("Item clicked"); }});Updating the DOM is not free, it actually costs some performance, so it is worth being careful with it.
for (let i = 0; i < 1000; i++) { document.body.append(document.createElement("div"));}This is considered bad because it updates the actual page 1000 separate times, which is slow.
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) { fragment.append(document.createElement("div"));}
document.body.append(fragment);This is better because all 1000 elements are first built up in memory, and the actual page is only updated once at the very end.
const users = ["A", "B", "C"];const ul = document.querySelector("#users");
ul.innerHTML = "";
users.forEach((user) => { const li = document.createElement("li"); li.textContent = user; ul.append(li);});element.innerHTML = userInput; // dangerousThis is risky because if userInput contains harmful code, it can actually run on your page. This kind of attack is called XSS (Cross-Site Scripting).
textContent instead of innerHTML when you can, since it is safer.