DOM Manipulation
Learn how to dynamically alter the structure, style, and content of a web page using JavaScript.
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
Guest User
Software Engineer
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use
textContentto safely change text; avoidinnerHTMLfor user input. - Use
classListtoadd(),remove(), ortoggle()CSS classes. - Use
setAttribute()to modify HTML attributes. document.createElement()makes an element in memory; you mustappend()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.