JavaScript DOM Manipulation - Creating, Modifying and Removing Elements
Description
DOM (Document Object Model) manipulation is a core aspect of JavaScript that allows developers to dynamically create, modify, and remove HTML elements on web pages. This enables interactive and responsive web applications without requiring page reloads.
1. Selecting Elements
Example: Basic Element Selection
// Select by ID
const header = document.getElementById('header');
// Select by class name (returns HTMLCollection)
const items = document.getElementsByClassName('item');
// Select by tag name (returns HTMLCollection)
const paragraphs = document.getElementsByTagName('p');
// Modern selectors (returns NodeList)
const mainContent = document.querySelector('#main-content');
const allButtons = document.querySelectorAll('.btn');
2. Creating New Elements
Example: Creating and Appending Elements
// Create a new div element
const newDiv = document.createElement('div');
// Add content and attributes
newDiv.textContent = 'This is a new div!';
newDiv.className = 'custom-div';
newDiv.id = 'my-new-div';
// Append to the body
document.body.appendChild(newDiv);
// Or append to a specific element
const container = document.getElementById('container');
container.appendChild(newDiv);
3. Modifying Element Content
Example: Changing Text and HTML Content
const element = document.getElementById('my-element');
// Change text content (escapes HTML)
element.textContent = 'New text content';
// Change HTML content (renders HTML)
element.innerHTML = '<strong>Bold text</strong> and <em>italic text</em>';
// Using insertAdjacentHTML for more control
element.insertAdjacentHTML('beforeend', '<p>New paragraph added</p>');
4. Modifying Attributes and Classes
Example: Working with Attributes and Classes
const image = document.getElementById('my-image');
// Set attributes
image.setAttribute('src', 'new-image.jpg');
image.setAttribute('alt', 'Description of image');
// Get attributes
const src = image.getAttribute('src');
// Remove attributes
image.removeAttribute('alt');
// Class manipulation
const box = document.getElementById('box');
box.classList.add('active', 'highlight'); // Add multiple classes
box.classList.remove('inactive'); // Remove class
box.classList.toggle('hidden'); // Toggle class
box.classList.contains('active'); // Check if class exists
5. Modifying Styles
Example: Dynamic Style Changes
const element = document.getElementById('styled-element');
// Direct style manipulation
element.style.color = 'blue';
element.style.backgroundColor = '#f0f0f0';
element.style.fontSize = '18px';
// Multiple styles at once
Object.assign(element.style, {
padding: '10px',
margin: '20px',
border: '1px solid black'
});
// Using CSS classes (preferred method)
element.classList.add('highlighted');
6. Removing Elements
Example: Removing Elements from DOM
// Remove a specific element
const elementToRemove = document.getElementById('remove-me');
elementToRemove.remove();
// Remove child element from parent
const parent = document.getElementById('parent-container');
const child = document.getElementById('child-element');
parent.removeChild(child);
// Remove all children
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
7. Event Handling with Dynamic Elements
Example: Adding Event Listeners
// Add click event to existing button
const button = document.getElementById('my-button');
button.addEventListener('click', function() {
alert('Button clicked!');
});
// Event delegation for dynamically created elements
document.body.addEventListener('click', function(event) {
if (event.target.classList.contains('dynamic-btn')) {
console.log('Dynamic button clicked:', event.target.textContent);
}
});
8. Practical Example: Dynamic List Management
// Create a dynamic todo list
function addTodoItem(text) {
const list = document.getElementById('todo-list');
// Create new list item
const li = document.createElement('li');
li.className = 'todo-item';
// Add text
const span = document.createElement('span');
span.textContent = text;
// Add delete button
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.className = 'delete-btn';
deleteBtn.onclick = function() {
li.remove();
};
// Assemble the item
li.appendChild(span);
li.appendChild(deleteBtn);
// Add to list
list.appendChild(li);
}
// Usage
addTodoItem('Learn JavaScript');
addTodoItem('Practice DOM manipulation');
9. Performance Considerations
Example: Efficient DOM Manipulation
// Use DocumentFragment for multiple additions
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
div.textContent = `Item ${i}`;
fragment.appendChild(div);
}
// Single DOM update
document.getElementById('container').appendChild(fragment);
// Batch style changes
const element = document.getElementById('my-element');
element.style.cssText = 'color: red; font-size: 16px; padding: 10px;';
Key Points to Remember:
- Use querySelector/querySelectorAll for modern CSS selector support
- Prefer classList over className for better class management
- Use event delegation for dynamically created elements
- Batch DOM operations for better performance
- Use DocumentFragment when adding multiple elements
- Always check if elements exist before manipulating them
These techniques form the foundation of interactive web development and are essential for creating dynamic, responsive user interfaces.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.