Understanding how to manipulate the DOM (Document Object Model) is crucial for creating dynamic, interactive web pages. The DOM represents a web page so that programs can change the document structure, style, and content. This guide will walk you through selecting, modifying, creating, and removing elements, as well as managing events in JavaScript.
Selecting elements is the first step in DOM manipulation. JavaScript provides various methods to access and select HTML elements.
getElementByIdThe getElementById method is used to select a single element by its unique ID. This is often the most efficient way to access an element because IDs are unique within the document.
let element = document.getElementById('myElement');
getElementsByClassNameThe getElementsByClassName method returns a live HTMLCollection of elements with the given class name. This method is useful for selecting multiple elements that share the same class.
let elements = document.getElementsByClassName('myClass');
querySelector and querySelectorAllThe querySelector method returns the first element that matches a specified CSS selector, while querySelectorAll returns a static NodeList of all matching elements. These methods are powerful for complex selections.
let firstElement = document.querySelector('.myClass');
let allElements = document.querySelectorAll('.myClass');
Once elements are selected, you can modify their content, attributes, and styles to change their appearance and behavior.
To change the text content of an element, use the textContent or innerText properties. textContent is generally preferred as it includes all text within an element, while innerText only includes visible text.
element.textContent = 'New text content';