DOM Manipulation
DOM Manipulation
The Document Object Model (DOM) represents the structure of a webpage.
Selecting Elements
// Single element
const element = document.getElementById('myId');
const element = document.querySelector('.myClass');// Multiple elements
const elements = document.getElementsByClassName('myClass');
const elements = document.querySelectorAll('.myClass');
Creating Elements
const div = document.createElement('div');
div.textContent = 'Hello, World!';
div.className = 'greeting';
div.id = 'myDiv';document.body.appendChild(div);
Modifying Elements
const element = document.querySelector('#myElement');// Content
element.textContent = 'New text';
element.innerHTML = 'Bold text';
// Attributes
element.setAttribute('data-id', '123');
element.getAttribute('data-id');
element.removeAttribute('data-id');
// Classes
element.classList.add('active');
element.classList.remove('active');
element.classList.toggle('active');
element.classList.contains('active');
// Styles
element.style.color = 'red';
element.style.backgroundColor = 'blue';
Removing Elements
const element = document.querySelector('#toRemove');// Modern way
element.remove();
// Old way
element.parentNode.removeChild(element);
Traversing the DOM
const element = document.querySelector('.item');// Parent
element.parentElement;
element.parentNode;
// Children
element.children;
element.firstElementChild;
element.lastElementChild;
// Siblings
element.nextElementSibling;
element.previousElementSibling;