~/
hackweb.dev
JavaScript DOM Manipulation
Quiz
⌘K
...
~/
/tutorials
/js/js-dom-manipulation/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/17js-dom-manipulation
Write
Preview
Diff
# JavaScript DOM Manipulation The DOM (Document Object Model) represents HTML as a JavaScript object tree. JavaScript can read, create, and modify HTML elements. ## Selecting Elements ```javascript // By ID let element = document.getElementById("myId"); // By CSS selector (first match) let button = document.querySelector(".btn"); // All matching elements let items = document.querySelectorAll(".item"); ``` **Remember:** `querySelector` returns the first match, `querySelectorAll` returns all matches. ## Changing Content ```javascript let el = document.getElementById("demo"); el.textContent = "New text"; // Plain text el.innerHTML = "<strong>Bold</strong>"; // HTML content ``` **Tip:** Use `textContent` over `innerHTML` — it's safer against XSS attacks. ## Changing Styles ```javascript let box = document.getElementById("box"); box.style.backgroundColor = "red"; box.style.fontSize = "20px"; // Multiple styles at once box.style.cssText = "background: blue; color: white;"; ``` **Remember:** Style properties use camelCase (`backgroundColor`, not `background-color`). ## Creating Elements ```javascript let div = document.createElement("div"); div.textContent = "Hello World"; div.className = "container"; document.body.appendChild(div); ``` ## Manipulating Classes ```javascript let box = document.getElementById("box"); box.classList.add("active"); box.classList.remove("inactive"); box.classList.toggle("visible"); box.classList.contains("active"); // true/false ``` ## Complete Example: Todo List ```javascript let input = document.getElementById("todo-input"); let btn = document.getElementById("add-btn"); let list = document.getElementById("todo-list"); btn.addEventListener("click", () => { let text = input.value.trim(); if (!text) return; let li = document.createElement("li"); li.textContent = text; list.appendChild(li); input.value = ""; }); ``` ## Best Practices - **Cache selectors** — Don't query the DOM repeatedly - **Use textContent** — Safer than innerHTML - **Use CSS classes for styling** — Prefer `classList` over direct `style` manipulation - **Batch DOM changes** — Minimize reflows - **Check if element exists** — Prevent null errors ## Common Mistakes - **Querying too much** — Cache your selectors - **Using innerHTML with user data** — Security risk (XSS) - **Forgetting to append** — Element won't appear without `appendChild` - **Using camelCase for style properties** — `fontSize`, not `font-size` - **Not trimming input** — Check for empty values
No changes yet
Reset to original
Submit suggestion
cancel