DOM Manipulation with JavaScript

What Is the DOM?

DOM = Document Object Model. It’s a live, programmable version of your webpage.

Every HTML element becomes a JavaScript object that you can:

Selecting Elements

Get element by ID

const title = document.getElementById("main-title");
      

Query selector

const box = document.querySelector(".my-box");
      

Multiple elements

const items = document.querySelectorAll("li");
      

Changing Text

const h1 = document.getElementById("title");
h1.textContent = "New Title!";
      

Changing CSS

const box = document.querySelector(".box");
box.style.backgroundColor = "red";
box.style.padding = "20px";
      

Changing HTML

const content = document.getElementById("content");
content.innerHTML = "<h2>Injected HTML</h2>";
      

Creating New Elements

const p = document.createElement("p");
p.textContent = "This is a new paragraph!";
document.body.appendChild(p);
      

Deleting Elements

const removeMe = document.getElementById("trash");
removeMe.remove();
      

Adding Event Listeners

const btn = document.getElementById("clickBtn");

btn.addEventListener("click", () => {
  alert("Button clicked!");
});
      

Practical Example — Counter

<button id="plus">+</button>
<span id="count">0</span>
<button id="minus">-</button>

<script>
let count = 0;

document.getElementById("plus").onclick = () => {
  count++;
  document.getElementById("count").textContent = count;
};

document.getElementById("minus").onclick = () => {
  count--;
  document.getElementById("count").textContent = count;
};
</script>
      

What’s Next?

Next you’ll learn how to style webpages using CSS Flexbox to create clean modern layouts.