JavaScript Tutorial · JavaScript in the Browser · Lesson 41 of 44

JavaScript DOM Manipulation

Create, insert and remove elements; change classes, styles and attributes.

Creating elements

document.createElement() makes a new element; append() adds it to the page:

Build a list with createElementTry it yourself
<ul id="list"></ul>
<script>
  const list = document.getElementById("list");
  for (const lang of ["HTML", "CSS", "JavaScript"]) {
    const li = document.createElement("li");
    li.textContent = lang;
    list.append(li);
  }
  const note = document.createElement("p");
  note.textContent = `The list has ${list.children.length} items.`;
  list.after(note);
</script>

Classes, styles and attributes

  • el.classList.add/remove/toggle("name") — the best way to change styling (keep the styles in CSS).
  • el.style.color = "red" — inline styles for one-off values.
  • el.setAttribute("href", url), el.dataset.id — attributes and data-* attributes.
Classes, styles and data attributesTry it yourself
<style>
  .card { padding: 12px; border: 1px solid #ccc; border-radius: 8px; font-family: sans-serif; }
  .highlight { background: #fff3c4; border-color: #e0b400; }
</style>
<div class="card" id="card" data-user-id="42">Card for user</div>
<script>
  const card = document.getElementById("card");
  card.classList.add("highlight");
  card.textContent += ` #${card.dataset.userId}`;
  card.style.fontWeight = "bold";
  card.setAttribute("title", "I have a tooltip");
</script>

Removing elements

el.remove() removes an element from the page.

Test yourself

Which property toggles a CSS class on an element?

  1. className.toggle
  2. classList
  3. style.class
  4. cssClass
Show answer

Answer: classList