To manipulate the Document Object Model (DOM) using JavaScript, you can follow these steps:
getElementById()
, getElementsByTagName()
, getElementsByClassName()
, or querySelector()
.Example:
const element = document.getElementById('myElement');
Example:
element.innerHTML = 'New content'; // Change the content
element.style.backgroundColor = 'red'; // Change the background color
element.classList.add('highlight'); // Add a class
Example:
const newElement = document.createElement('div'); // Create a new element
element.appendChild(newElement); // Add the new element as a child
element.parentNode.removeChild(element); // Remove an existing element
Example:
element.addEventListener('click', function() {
console.log('Element clicked!');
});
These are some basic examples of how to manipulate the DOM using JavaScript. There are many more methods and properties available to perform various tasks like traversing the DOM, handling forms, or animating elements.