Skip to main content
JavaScript Basics
CHAPTER 16 Beginner

JavaScript DOM Manipulation

Updated: May 12, 2026
30 min read

# JavaScript DOM Manipulation

In the last chapter, we learned how to find and select elements on a webpage. But selecting an element is only half the battle. Now, we need to learn how to change them!

In this chapter, we will learn how to manipulate the DOM by changing text, altering CSS styles on the fly, adding classes, and creating brand new HTML elements dynamically.

1. Introduction

DOM Manipulation is the core of modern interactive web development. When a user clicks a "Dark Mode" button, JavaScript manipulates the DOM to change the background colors. When new tweets load as you scroll down, JavaScript is dynamically creating new HTML elements and injecting them into the DOM.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Change the text and HTML content of an element.
  • Change the attributes of an element (like image src or link href).
  • Modify CSS styles directly using the style property.
  • Manage CSS classes using classList (add, remove, toggle).
  • Create and append brand new HTML elements using createElement().
  • Build a Dynamic Card Generator mini-project.

3. Changing Content

The two most common properties to change content are innerHTML and textContent.

  • innerHTML: Reads and writes raw HTML tags.
  • textContent: Reads and writes raw text, ignoring all HTML tags (Safer!).

4. Changing Attributes

You can change any HTML attribute (like src, href, alt, disabled) using the setAttribute() method or by accessing the property directly.

5. Changing Styles

You can manipulate CSS directly via the .style property. Note that multi-word CSS properties (like background-color) become camelCase in JavaScript (backgroundColor).

---

6. Real-world Examples & Code Snippets

Example 1: innerHTML vs textContent

html
123456789101112
<!-- Example HTML -->
<div id="target1"></div>
<div id="target2"></div>

<script>
// Example JavaScript
let t1 = document.getElementById("target1");
let t2 = document.getElementById("target2");

t1.innerHTML = "<strong>Bold Text</strong>"; // Renders bold text
t2.textContent = "<strong>Bold Text</strong>"; // Renders literally "<strong>Bold Text</strong>"
</script>

Example 2: Changing an Image Source

html
1234567891011
<!-- Example HTML -->
<img id="profilePic" src="avatar.jpg" alt="Avatar">

<script>
// Example JavaScript
let img = document.getElementById("profilePic");
// Change the source attribute
img.src = "new_avatar.jpg";
// Change the alt attribute
img.alt = "Updated Avatar";
</script>

Example 3: Disabling a Button

You can change attributes to disable form elements dynamically.

html
123456789
<!-- Example HTML -->
<button id="submitBtn">Submit Form</button>

<script>
// Example JavaScript
let btn = document.getElementById("submitBtn");
btn.disabled = true; // Button turns grey and cannot be clicked
btn.innerHTML = "Processing...";
</script>

Example 4: Changing CSS Styles Directly

html
12345678910111213
<!-- Example HTML -->
<p id="alertBox">Error loading data.</p>

<script>
// Example JavaScript
let box = document.getElementById("alertBox");

// Notice camelCase: backgroundColor, not background-color
box.style.backgroundColor = "red";
box.style.color = "white";
box.style.padding = "15px";
box.style.borderRadius = "5px";
</script>

Example 5: The classList API (Best Practice)

Changing individual styles directly is messy. The professional way is to define a class in CSS, and use JavaScript to add or remove that class using classList.

html
123456789101112131415161718
<!-- Example HTML -->
<style>
/* Example CSS */
.highlight { background: yellow; font-weight: bold; border: 2px solid orange; }
</style>

<p id="promo">Special Discount Inside!</p>

<script>
// Example JavaScript
let promo = document.getElementById("promo");

// Add a class
promo.classList.add("highlight");

// Remove a class
// promo.classList.remove("highlight");
</script>

Example 6: classList.toggle()

Toggle is incredibly useful. If the element HAS the class, it removes it. If it DOESN'T have the class, it adds it. (Perfect for Dark Mode or dropdown menus).

html
1234567891011
<!-- Example HTML -->
<button onclick="toggleMenu()">Toggle Menu</button>
<div id="dropdown" class="hidden">...</div>

<script>
// Example JavaScript
function toggleMenu() {
    let menu = document.getElementById("dropdown");
    menu.classList.toggle("hidden");
}
</script>

Example 7: Creating New HTML Elements

To create a brand new element that doesn't exist in the HTML file, use document.createElement().

javascript
123456
// Example JavaScript
// 1. Create an empty <li> tag in memory
let newListItem = document.createElement("li");

// 2. Add text to it
newListItem.textContent = "I am a new item!";

Example 8: Appending Elements to the DOM

Creating an element doesn't put it on the screen. You must "append" it to an existing parent element.

html
123456789101112131415
<!-- Example HTML -->
<ul id="myList">
    <li>Item 1</li>
</ul>

<script>
// Example JavaScript
let ul = document.getElementById("myList");

let li = document.createElement("li");
li.textContent = "Item 2";

// Add it to the end of the ul
ul.appendChild(li); 
</script>

Example 9: Prepending Elements

If you want to add the element to the *beginning* of the list (like a new chat message), use prepend().

javascript
123456
// Example JavaScript
let ul = document.getElementById("myList");
let li = document.createElement("li");
li.textContent = "I am first!";

ul.prepend(li);

Example 10: Removing Elements completely

You can remove elements from the DOM using the remove() method.

html
12345678
<!-- Example HTML -->
<div id="adBanner">Buy Now!</div>

<script>
// Example JavaScript
let ad = document.getElementById("adBanner");
ad.remove(); // The div completely vanishes from the HTML
</script>

---

7. Common Mistakes for Beginners

  1. 1. Using CSS syntax in JS styles: Writing element.style.font-size = "20px" will crash. You MUST use camelCase: element.style.fontSize.
  1. 2. Forgetting to append created elements: document.createElement("div") creates a div floating in the browser's memory. It will never show up on screen until you appendChild() it to something.
  1. 3. Using innerHTML for user input: If you take user input from a prompt and use innerHTML to display it, a malicious user can type <script>hack()</script> and execute code on your site! ALWAYS use textContent when displaying user input.

8. Best Practices

  • Avoid changing .style properties manually unless necessary. It is much cleaner to create a CSS class and use .classList.add() or .classList.toggle().
  • When creating many elements in a loop, avoid appending them one-by-one directly to the DOM, as this causes the browser to re-paint the screen multiple times (which is slow). Create them in memory, append them to a temporary container, and append the container to the DOM once.

9. Mini Project: Dynamic Card Generator

Let's build a tool that generates user profile cards dynamically using inputs and createElement().

HTML:

html
123456789101112131415161718192021222324252627282930313233
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; padding: 20px; background: #eee;}
        .form-box { background: white; padding: 20px; border-radius: 8px; width: 300px; margin-bottom: 20px;}
        input { display: block; width: 90%; padding: 8px; margin-bottom: 10px; }
        button { background: #007bff; color: white; border: none; padding: 10px; cursor: pointer; border-radius: 4px; width: 100%;}
        
        #cardContainer { display: flex; gap: 15px; flex-wrap: wrap; }
        
        .user-card { background: white; padding: 15px; border-radius: 8px; width: 200px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); border-top: 5px solid #007bff;}
        .user-card h3 { margin: 0 0 5px 0; }
        .user-card p { color: #555; margin: 0; }
        .delete-btn { background: #dc3545; padding: 5px; margin-top: 10px; font-size: 12px; }
    </style>
</head>
<body>

    <div class="form-box">
        <h3>Create User</h3>
        <input type="text" id="nameInput" placeholder="User Name">
        <input type="text" id="roleInput" placeholder="User Role (e.g. Admin)">
        <button onclick="createCard()">Generate Card</button>
    </div>

    <div id="cardContainer"></div>

    <script src="cards.js"></script>
</body>
</html>

cards.js:

javascript
12345678910111213141516171819202122232425262728293031323334353637383940414243
// Example JavaScript
function createCard() {
    let name = document.getElementById("nameInput").value;
    let role = document.getElementById("roleInput").value;
    let container = document.getElementById("cardContainer");

    if (name === "" || role === "") {
        alert("Please fill out both fields");
        return;
    }

    // 1. Create the main card div
    let card = document.createElement("div");
    card.classList.add("user-card");

    // 2. Create the heading
    let title = document.createElement("h3");
    title.textContent = name;

    // 3. Create the paragraph
    let desc = document.createElement("p");
    desc.textContent = role;
    
    // 4. Create a delete button
    let delBtn = document.createElement("button");
    delBtn.textContent = "Delete";
    delBtn.classList.add("delete-btn");
    delBtn.onclick = function() {
        card.remove(); // Removes this specific card!
    };

    // 5. Assemble the elements
    card.appendChild(title);
    card.appendChild(desc);
    card.appendChild(delBtn);

    // 6. Append the finished card to the container
    container.appendChild(card);
    
    // Clear inputs
    document.getElementById("nameInput").value = "";
    document.getElementById("roleInput").value = "";
}

10. Exercises

  1. 1. Create a button with an id of submitBtn. Write JS to change its .textContent to "Sending...".
  1. 2. Create a <div id="box"></div>. Write JS to add the class active to it using classList.
  1. 3. Use document.createElement() to create an <h1> element, set its text to "Hello", and appendChild it to document.body.

11. MCQs (Multiple Choice Questions)

Q1: Which property should you use to safely display user input without risking script injection? A) innerHTML B) textContent C) outerHTML D) writeHTML *Answer: B*

Q2: What is the correct way to change the background color of an element in JavaScript? A) element.style.background-color = "red"; B) element.css.backgroundColor = "red"; C) element.style.backgroundColor = "red"; D) element.color.background = "red"; *Answer: C*

Q3: Which method creates a new HTML element? A) document.newElement() B) document.build() C) document.createElement() D) document.appendElement() *Answer: C*

12. Interview Questions

Q: What is the difference between appendChild() and innerHTML = "..."? *A: innerHTML wipes out the existing content of the element and completely parses the new string from scratch. It destroys existing event listeners on child elements. appendChild() takes an existing DOM node object and attaches it to the parent without disrupting the other children or triggering a massive re-parse.*

Q: Explain how Cross-Site Scripting (XSS) occurs with innerHTML. *A: If a developer takes unfiltered text from a user (like a blog comment) and renders it using innerHTML, the user can submit a <script> tag. The browser will parse it as real HTML and execute the malicious JavaScript against anyone viewing the page.*

13. FAQs

Q: Can I remove multiple classes at once? *A: Yes! You can pass multiple arguments: element.classList.remove("class1", "class2");.*

14. Summary

  • innerHTML processes HTML tags. textContent only processes text.
  • Change HTML attributes (like src) directly via properties.
  • CSS styles accessed via JS use camelCase (backgroundColor).
  • classList.add(), .remove(), and .toggle() are the best ways to change styles.
  • Build elements with createElement() and attach them with appendChild().

15. Next Chapter Recommendation

So far, our buttons only work because we added onclick="" directly into our HTML code. This is considered an outdated, messy practice. In the next chapter, JavaScript Events, we will learn the modern way to listen for clicks, hovers, keyboard presses, and form submissions entirely within JavaScript!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·