šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
JS MASTER CLASS /// MASTER THE ENGINE /// BUILD LOGIC /// ASYNC PATTERNS /// JS MASTER CLASS /// MASTER THE ENGINE ///

JS Manipulation | JavaScript Tutorial - In-Depth Guide

Learn about JS Manipulation in this comprehensive JavaScript tutorial for web development. Master the art of modifying element structure, attributes, and classes. Learn the difference between destructive updates and state toggling.

⚔ Total XP: 0|šŸ’» javascript XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core logic.

Quick Quiz //

What is the primary advantage discussed here?


šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Once you've selected a DOM element, manipulation is how you actually change it — editing its content, attributes, and CSS classes, or removing it entirely. This lesson covers innerHTML versus textContent, setAttribute/removeAttribute, the classList API (add, remove, toggle), and safely deleting elements with remove().

1JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 1

Selection was just the start. Now we learn how to modify the structure, attributes, and classes of our elements surgically.

āœ•
—
+
// Structural Surgery
localhost:3000
Terminal
Code executed.

2JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 2

innerHTML vs textContent: innerHTML parses strings as HTML. It

āœ•
—
+
const box = document.querySelector('.container');
box.innerHTML = '<strong>Warning!</strong>';
localhost:3000
Terminal
Code executed.

3JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 3

setAttribute allows you to change ANY attribute on an element, like ''src' for images or 'href' for links.

āœ•
—
+
const img = document.querySelector('img');
img.setAttribute('src', 'logo-dark.png');
localhost:3000
Terminal
Code executed.

4JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 4

classList is the modern way to manage CSS classes. You can .add(), .remove(), or .toggle() classes easily.

āœ•
—
+
const btn = document.querySelector('.btn');
btn.classList.add('active');
btn.classList.toggle('hidden');
localhost:3000
Terminal
Code executed.

5JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 5

Deleting elements is simple. The .remove() method deletes the element from the DOM entirely.

āœ•
—
+
const alert = document.querySelector('.alert');
alert.remove(); // Gone forever!
localhost:3000
Terminal
> Gone forever!

6JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 6

Attributes can also be checked or removed using hasAttribute() and removeAttribute().

āœ•
—
+
if (btn.hasAttribute('disabled')) {
  btn.removeAttribute('disabled');
}
localhost:3000
Terminal
Code executed.

7JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 7

State Control: By toggling classes and attributes, you can create interactive menus, modals, and themes.

āœ•
—
+
<h1>UI: Managed</h1>
localhost:3000
Terminal
Code executed.

8JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 8

Manipulation mastered! You are now the surgeon of the web document.

āœ•
—
+
<h1>Doc: Modified</h1>
localhost:3000
Terminal
Code executed.

9JS Manipulation | JavaScript Tutorial - In-Depth Guide Part 9

Next, we' 'Style Modification' to create stunning visual transitions.

āœ•
—
+
<h1>Next: Styles</h1>
localhost:3000
Terminal
Code executed.

10Step-by-Step Breakdown

Selection was just the start. Now we learn how to modify the structure, attributes, and classes of our elements surgically.

innerHTML vs textContent: innerHTML parses strings as HTML. It

setAttribute allows you to change ANY attribute on an element, like ''src' for images or 'href' for links.

Checkpoint: Which property should you use to change the text of an element SAFELY (ignoring any HTML tags)?

  • →innerHTML
  • →textContent

classList is the modern way to manage CSS classes. You can .add(), .remove(), or .toggle() classes easily.

Deleting elements is simple. The .remove() method deletes the element from the DOM entirely.

Checkpoint: If you want to switch a class ''ON' if it's off, and 'OFF' if it's on, which method do you use?

  • →add()
  • →remove()
  • →toggle()

Attributes can also be checked or removed using hasAttribute() and removeAttribute().

State Control: By toggling classes and attributes, you can create interactive menus, modals, and themes.

Checkpoint: How do you add a class to an element without overwriting existing classes?

  • →className = 'new'
  • →classList.add('new')

Manipulation mastered! You are now the surgeon of the web document.

Next, we' 'Style Modification' to create stunning visual transitions.

Level Up šŸš€

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Removing a Focused Element Silently Drops Keyboard Focus

Calling .remove() on an element that currently has keyboard focus (like a close button that just removed its own dialog) leaves focus nowhere, often resetting it to the document body. Move focus explicitly to a sensible nearby element right before or after removing the focused node.

SEO Implications

  • 1

    innerHTML Rewrites Can Wipe Out Content a Crawler Already Parsed

    Replacing a large content container's innerHTML after the initial render (e.g. to inject client-fetched data) means the meaningful text only exists after that JS runs. If a crawler doesn't execute it, the indexed version of the page may show stale or empty content instead.

Best Practices

Never Pass Unsanitized User Input to innerHTML

Setting innerHTML with a string that includes user-provided text (like a comment or a chat message) lets an attacker inject a `<script>` tag or malicious markup — a classic Cross-Site Scripting (XSS) vulnerability. Use textContent for plain text, or sanitize the HTML with a trusted library before rendering it.

Use classList Instead of Overwriting className Directly

Setting `element.className = 'new-class'` wipes out every other class already on that element. classList.add()/remove()/toggle() modify one class at a time without touching the rest, which is safer when other code or CSS frameworks depend on classes you don't control.

Frequent Bugs

THE BUG

A dynamic comment or chat feature is vulnerable to script injection.

THE FIX

This typically happens when user-submitted text is inserted with `element.innerHTML = userInput` instead of `element.textContent = userInput`. innerHTML parses the string as HTML, so a value like `<img src=x onerror=alert(1)>` executes as code; textContent always renders it as inert plain text.

Real-World Examples

Safely Toggling a Dropdown Menu's Open State

A navigation dropdown needed to open and close on click while keeping its accessibility attributes in sync, so the click handler toggled both a visual CSS class and the corresponding ARIA state together.

const menuButton = document.querySelector('.menu-toggle');
const menu = document.querySelector('.dropdown-menu');

menuButton.addEventListener('click', () => {
  const isOpen = menu.classList.toggle('open');
  menuButton.setAttribute('aria-expanded', String(isOpen));
});

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Mutating arrays while iterating over them

// Wrong items.forEach((item, index) => { if (item === 'remove') items.splice(index, 1); }); // Correct const newItems = items.filter(item => item !== 'remove');

The Solution //

Modifying an array's length or contents while looping through it (with a for loop or forEach) can cause elements to be skipped. Use methods like filter() or map() instead.

The Error //

Forgetting to await asynchronous functions

// Wrong const data = fetch('api/data'); console.log(data.json()); // Error // Correct const response = await fetch('api/data'); const data = await response.json();

The Solution //

If a function returns a Promise, you must use 'await' (or .then) to get its resolved value. Otherwise, your variable will hold a Promise object instead of the data.

Lesson Glossary

[01]innerHTML

A property that sets or gets the HTML markup contained within an element.

Code Preview
el.innerHTML = '<p>...</p>'

[02]classList

A property that returns a live DOMTokenList collection of the class attributes of the element.

Code Preview
el.classList

[03]setAttribute

Sets the value of an attribute on the specified element.

Code Preview
el.setAttribute('id', 'val')

[04]toggle

A classList method that adds a class if it's missing, and removes it if it's already present.

Code Preview
el.classList.toggle('x')

[05]remove()

A method used to delete an element from the document tree entirely.

Code Preview
el.remove()

[06]XSS

Cross-Site Scripting; a security vulnerability often caused by unsafely using innerHTML with user-provided data.

Code Preview
Security Risk

Continue Learning