How to change the page with the DOM

Select and change an element

The DOM is the browser's object model of the document. Check a query before using it because no match returns null.

<p id="message">Old text</p>
<script>
  const message = document.querySelector("#message");
  if (message) {
    message.textContent = "JavaScript changed this text.";
  }
</script>

Change classes and attributes

Classes keep presentation in CSS. Attribute methods update element metadata and state.

const card = document.querySelector(".card");
if (card) {
  card.classList.add("featured");
  card.setAttribute("aria-label", "Featured course");
  console.log(card.getAttribute("aria-label"));
}

Create and append elements

Create nodes, set text, then attach them. This works without constructing an HTML string.

const list = document.querySelector("#topics");
const item = document.createElement("li");
item.textContent = "Events";
list?.append(item);

Update the DOM safely

  • Load scripts with defer or place them after the relevant markup
  • Prefer textContent for untrusted text
  • Use innerHTML only with trusted, intentionally parsed markup
  • Batch repeated changes and avoid unnecessary DOM work inside tight loops