JavaScript DOM Manipulation
# 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
srcor linkhref).
-
Modify CSS styles directly using the
styleproperty.
-
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
Example 2: Changing an Image Source
Example 3: Disabling a Button
You can change attributes to disable form elements dynamically.
Example 4: Changing CSS Styles Directly
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.
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).
Example 7: Creating New HTML Elements
To create a brand new element that doesn't exist in the HTML file, use document.createElement().
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.
Example 9: Prepending Elements
If you want to add the element to the *beginning* of the list (like a new chat message), use prepend().
Example 10: Removing Elements completely
You can remove elements from the DOM using the remove() method.
---
7. Common Mistakes for Beginners
-
1.
Using CSS syntax in JS styles: Writing
element.style.font-size = "20px"will crash. You MUST use camelCase:element.style.fontSize.
-
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 youappendChild()it to something.
-
3.
Using
innerHTMLfor user input: If you take user input from a prompt and useinnerHTMLto display it, a malicious user can type<script>hack()</script>and execute code on your site! ALWAYS usetextContentwhen displaying user input.
8. Best Practices
-
Avoid changing
.styleproperties 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:
cards.js:
10. Exercises
-
1.
Create a button with an id of
submitBtn. Write JS to change its.textContentto "Sending...".
-
2.
Create a
<div id="box"></div>. Write JS to add the classactiveto it usingclassList.
-
3.
Use
document.createElement()to create an<h1>element, set its text to "Hello", andappendChildit todocument.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
-
innerHTMLprocesses HTML tags.textContentonly 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 withappendChild().
15. Next Chapter Recommendation
So far, our buttons only work because we addedonclick="" 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!