Back to Tutorials
JavaScript
25 min read
Sahasransu Satpathy
2/10/2026

JavaScript DOM Manipulation Examples

Learn how to interact with the DOM, modify elements, and handle events using JavaScript

Introduction

The Document Object Model (DOM) allows you to interact with your HTML elements dynamically using JavaScript. This tutorial covers practical examples for beginners.


Step 1: Selecting Elements

Use query selectors to target elements:

// Select by ID
const heading = document.getElementById('main-heading');

// Select by class
const items = document.getElementsByClassName('list-item');

// Select using querySelector
const firstItem = document.querySelector('.list-item');

// Select all using querySelectorAll
const allItems = document.querySelectorAll('.list-item');

Step 2: Changing Content

Modify text and HTML content dynamically:

heading.textContent = "DOM Manipulation Example";
heading.innerHTML = "<em>DOM Updated!</em>";

Step 3: Changing Styles

Update CSS styles using JavaScript:

heading.style.color = "blue";
heading.style.fontSize = "2rem";

Step 4: Creating and Appending Elements

Add new elements to the DOM:

const newItem = document.createElement('li');
newItem.textContent = "New List Item";
const list = document.querySelector('ul');
list.appendChild(newItem);

Step 5: Removing Elements

Remove elements dynamically:

const firstListItem = document.querySelector('li');
firstListItem.remove();

Step 6: Handling Events

Attach event listeners to elements:

const button = document.querySelector('button');
button.addEventListener('click', () => {
  alert("Button clicked!");
});

Step 7: Mini Project Example – Interactive List

Create a simple interactive list where users can add and remove items:

<input id="itemInput" placeholder="Add a list item" />
<button id="addBtn">Add Item</button>
<ul id="itemList"></ul>
const addBtn = document.getElementById('addBtn');
const itemInput = document.getElementById('itemInput');
const itemList = document.getElementById('itemList');

addBtn.addEventListener('click', () => {
  const li = document.createElement('li');
  li.textContent = itemInput.value;
  li.addEventListener('click', () => li.remove()); // Remove on click
  itemList.appendChild(li);
  itemInput.value = '';
});

Conclusion

You now know how to select, modify, add, and remove elements in the DOM and handle events effectively. Practice these examples to become confident in DOM manipulation.


SEO Suggestions:

  • Main keywords: JavaScript DOM manipulation, DOM examples, interactive JavaScript tutorial, JS beginner guide
  • Meta description: Learn JavaScript DOM manipulation with practical examples. Modify elements, handle events, and create interactive web pages step-by-step.
  • Catchy title suggestions: "JavaScript DOM Manipulation – Step-by-Step Examples", "Interactive DOM Manipulation with JavaScript"

Previous Tutorial

Browse All Tutorials