iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

DOM Methods

DOM methods read and change the document tree. The modern API is small and consistent — most patterns are variations of find element → do something to it.

The methods you'll use weekly

MethodPurpose
document.querySelector(sel)First element matching a CSS selector.
document.querySelectorAll(sel)Static NodeList of all matches.
document.getElementById(id)Direct lookup, slightly faster.
el.append(...) / el.prepend(...)Add children (accepts strings or nodes).
el.remove()Remove from the DOM.
el.cloneNode(deep)Copy a node — pass true for descendants too.
el.closest(sel)Walk up to the nearest matching ancestor.
el.matches(sel)Does this element match the selector?
el.insertAdjacentHTML(pos, html)Parse HTML into a position around the element.
document.createElement(tag)Build a new element in memory.

Common patterns

JS
// Create and append
const li = document.createElement("li");
li.textContent = "New item";
li.classList.add("todo");
document.querySelector("#list").append(li);

// One-shot insert
document.querySelector("#list").insertAdjacentHTML("beforeend", `<li>Quick</li>`);

// Bulk operations — work in a DocumentFragment to avoid layout thrashing
const frag = document.createDocumentFragment();
for (const name of names) {
  const li = document.createElement("li");
  li.textContent = name;
  frag.append(li);
}
list.append(frag);
Tip: Default to textContent over innerHTML. The latter parses HTML — risky with untrusted input, and slower for plain text.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from DOM Methods!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Select the first .btn on the page.

const btn = document. ('.btn');

Test yourself

Q1. First element matching a CSS selector comes from…
Q2. Add an element near another with…
Q3. Walk up to the nearest matching ancestor with…

Discussion

Loading…