JavaScript provides various methods to access and manipulate DOM elements. Let's explore these methods in detail.
1. getElementById()
This method retrieves an element by its ID.
const titleElement = document.getElementById('title');
console.log(titleElement.innerText); // Outputs: Hello, World!
2. getElementsByClassName()
This method returns a live HTMLCollection of elements with the specified class name.
const descriptionElements = document.getElementsByClassName('description');
console.log(descriptionElements[0].innerText); // Outputs: This is a sample paragraph.
3. getElementsByTagName()
This method returns a live HTMLCollection of elements with the specified tag name.
const listItems = document.getElementsByTagName('li');
console.log(listItems.length); // Outputs: 3
4. querySelector()
This method returns the first element that matches a specified CSS selector.
const firstListItem = document.querySelector('li');
console.log(firstListItem.innerText); // Outputs: Item 1
5. querySelectorAll()
This method returns a static NodeList of all elements that match a specified CSS selector.
const allListItems = document.querySelectorAll('li');
allListItems.forEach(item => console.log(item.innerText));
// Outputs: Item 1, Item 2, Item 3