DOM Manipulation β Changing the Screen with JavaScript
After completing this topic
You will understand what the DOM is, and you will learn the basic methods for finding, modifying, and handling events for HTML elements using JavaScript.
What is the DOM?
When a browser reads HTML, it converts it into a tree structure. This tree is called the DOM (Document Object Model).
<div id="app">
<h1>Hello</h1>
<p class="intro">World</p>
</div>In the DOM, this HTML becomes:
document
βββ div#app
βββ h1 β "Hello"
βββ p.intro β "World"JavaScript can read, add, delete, and modify the nodes in this tree. This is how the screen changes.
Finding Elements
// Find by ID
const app = document.getElementById("app");
// Find by CSS selector (first one)
const title = document.querySelector("h1");
const intro = document.querySelector(".intro");
// Find all by CSS selector
const allParagraphs = document.querySelectorAll("p");querySelector is the most versatile. You can use CSS selectors directly.
Modifying Content
const title = document.querySelector("h1");
// Change text
title.textContent = "μλ
νμΈμ";
// Change HTML
title.innerHTML = "μλ
<em>νμΈμ</em>";
// Change style
title.style.color = "blue";
title.style.fontSize = "24px";
// Add/remove class
title.classList.add("active");
title.classList.remove("active");
title.classList.toggle("active");textContent only contains text, while innerHTML includes HTML tags. Be careful when inserting user input into innerHTML, as it can create XSS vulnerabilities.
Creating and Adding Elements
const newItem = document.createElement("li");
newItem.textContent = "μ νλͺ©";
const list = document.querySelector("ul");
list.appendChild(newItem);Create a new element with createElement, and add it to an existing element with appendChild.
When adding multiple elements at once, using DocumentFragment can improve performance:
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const li = document.createElement("li");
li.textContent = `νλͺ© ${i}`;
fragment.appendChild(li);
}
list.appendChild(fragment);Event Handling
const button = document.querySelector("button");
button.addEventListener("click", (event) => {
console.log("ν΄λ¦λ¨!");
console.log(event.target); // The clicked element
});Register events with addEventListener. You can detect various events, such as clicks, input, and scrolling.
Why learn this when React exists?
Frameworks like React and Vue do not directly manipulate the DOM. They update the DOM automatically when the state changes.
However, understanding the principles of the DOM allows you to understand what the framework is doing for you. DOM knowledge is also needed when debugging, integrating libraries, and diagnosing performance issues.
Key Points
The DOM is a tree structure that represents HTML, and JavaScript manipulates this tree to change the screen. Use
querySelectorto find elements andaddEventListenerto handle events. Frameworks like React also manipulate the DOM internally.