- Published on
DOM Manipulation
DOM (Document Object Model) manipulation
refers to the process of dynamically interacting with the HTML structure of a web page. It involves selecting elements, modifying their properties, creating new elements, removing existing ones, and handling events.
Selecting elements
Selecting elements
is the process of targeting specific elements within the DOM tree
using JavaScript
. This is commonly done using methods like getElementById
, getElementsByClassName
, getElementsByTagName
, querySelector
, and querySelectorAll
.
Example:
// Selecting an element by its ID
const elementById = document.getElementById('myElementId')
// Selecting elements by class name
const elementsByClassName = document.getElementsByClassName('myClassName')
// Selecting elements by tag name
const elementsByTagName = document.getElementsByTagName('div')
// Selecting elements using CSS selectors
const elementByQuerySelector = document.querySelector('.myClass')
const elementsByQuerySelectorAll = document.querySelectorAll('p')
Modifying elements
Once elements are selected, their properties such as innerHTML
, textContent
, style
, classList
, etc., can be modified to change their appearance or content dynamically.
Example:
// Modifying innerHTML
elementById.innerHTML = 'New content'
// Modifying textContent
elementById.textContent = 'New text'
// Modifying styles
elementById.style.color = 'red'
// Adding or removing classes
elementById.classList.add('newClass')
elementById.classList.remove('oldClass')
Creating and removing elements
New elements can be created dynamically and appended to the DOM
using methods like createElement
, appendChild
, insertBefore
, etc. Similarly, existing elements can be removed using methods like removeChild
.
Example:
// Creating a new element
const newElement = document.createElement('div')
newElement.textContent = 'Newly created element'
// Appending the new element to an existing element
elementById.appendChild(newElement)
// Removing an existing element
elementById.removeChild(existingElement)
Event handling
Event handling
involves responding to user interactions such as clicks
, mouse movements
, key presses
, etc., by attaching event listeners
to DOM elements.
Example:
// Adding an event listener for click event
elementById.addEventListener('click', () => {
console.log('Element clicked!')
})
// Removing an event listener
const clickHandler = () => {
console.log('Element clicked!')
}
elementById.addEventListener('click', clickHandler)
// Removing the event listener
elementById.removeEventListener('click', clickHandler)