DOM Manipulation

Learn how to dynamically alter the structure, style, and content of a web page using JavaScript.

JavaScript6 min readConcept 42 of 62

Changing the Page

Once you have selected a DOM node, you can modify almost anything about it.

You can change its text, alter its CSS classes, update its HTML attributes (like disabled or src), or even completely delete it from the page.

The Virtual Paintbrush

Here are the most common ways to manipulate the DOM:

**Content**: Use node.textContent = 'Hello' to safely change text. Use node.innerHTML = '<b>Hi</b>' to inject HTML tags.

**Classes**: Use node.classList.add('active'), node.classList.remove(), or node.classList.toggle() to manage CSS classes.

**Attributes**: Use node.setAttribute('disabled', 'true') or node.removeAttribute('disabled').

Creating & Destroying

You aren't limited to modifying existing elements. You can create entirely new branches of the tree.

To add a new element: First, create it in memory using const newDiv = document.createElement('div'). Second, inject it into the live DOM using parentElement.appendChild(newDiv).

To destroy an element: Simply call node.remove().

The DOM Workshop

Use the control panel to execute JavaScript manipulation commands against the live Preview Card below.

The DOM Workshop

<div class="card">

Guest User

Software Engineer

iThe DOM is fully mutable. You can add classes (classList.add), change content (textContent), alter attributes (setAttribute), or even inject entirely new elements (appendChild).

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why is `textContent` preferred over `innerHTML` when displaying user input?
  2. 2How do you toggle a CSS class named 'hidden' on an element?
  3. 3What happens immediately after you run `const div = document.createElement('div')`?

Remember this

  • Use textContent to safely change text; avoid innerHTML for user input.
  • Use classList to add(), remove(), or toggle() CSS classes.
  • Use setAttribute() to modify HTML attributes.
  • document.createElement() makes an element in memory; you must append() it to make it visible.
  • Call .remove() on a node to destroy it.

Done with this concept?

Mark it complete to track your progress. No login needed.