How to get all elements by class in JavaScript?

Learn how to efficiently retrieve all elements by class in JavaScript, a crucial skill for navigating and extracting data from web pages. This guide provides a straightforward approach to mastering this technique.

Best practices

  • Use `document.getElementsByClassName('your-class-name')` when you need a live HTMLCollection that updates automatically as the DOM changes.

  • Prefer `document.querySelectorAll('.your-class-name')` for a static NodeList and when combining class selectors with other complex CSS selectors.

  • Remember that `NodeList` objects from `querySelectorAll` can be directly iterated with `forEach`, simplifying operations on multiple elements.

  • When fetching and manipulating external HTML content, utilize `DOMParser` to parse the HTML string and then apply `querySelectorAll` to select elements efficiently.

// Get elements by class name using getElementsByClassName
var elements = document.getElementsByClassName('example-class');
console.log(elements);

// Use querySelectorAll for more complex selectors
var elementsQuery = document.querySelectorAll('.example-class');
console.log(elementsQuery);

// Iterate over NodeList from querySelectorAll
document.querySelectorAll('.example-class').forEach(function(element) {
console.log(element);
});

// Example with a specific site
fetch('https://sandbox.oxylabs.io/products')
.then(response => response.text())
.then(html => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const items = doc.querySelectorAll('.product-item');
console.log(items);
})
.catch(error => console.error('Error fetching the data:', error));

Common issues

  • Ensure that the class name passed to `getElementsByClassName` or `querySelectorAll` does not include the dot prefix used in CSS, only the class name itself.

  • Be aware that `getElementsByClassName` returns a live HTMLCollection, which can impact performance if the DOM is being updated frequently.

  • Convert the NodeList returned by `querySelectorAll` into an array if you need methods like `map`, `filter`, or `reduce` that are not available on NodeList.

  • When using `querySelectorAll` in a loop or frequently called function, consider caching the result if the DOM does not change to improve performance.

// Incorrect: Includes the dot prefix, which should not be used with getElementsByClassName
var elements = document.getElementsByClassName('.example-class'); 
console.log(elements);

// Correct: Class name without the dot prefix
var elements = document.getElementsByClassName('example-class'); 
console.log(elements);

// Issue: Using getElementsByClassName in a frequently updated DOM
var dynamicElements = document.getElementsByClassName('dynamic-content');
setInterval(() => {
console.log(dynamicElements.length); // May cause performance issues
}, 1000);

// Better: Use querySelectorAll and update only when necessary
let staticElements = document.querySelectorAll('.dynamic-content');
console.log(staticElements.length);

// Incorrect: Trying to use Array methods directly on NodeList
document.querySelectorAll('.example-class').map(element => console.log(element));

// Correct: Convert NodeList to Array before using Array methods
Array.from(document.querySelectorAll('.example-class')).map(element => console.log(element));

// Issue: Not caching results of querySelectorAll in a loop
for (let i = 0; i < 1000; i++) {
let items = document.querySelectorAll('.item');
// Processing items
}

// Improved: Cache the NodeList outside the loop
let cachedItems = document.querySelectorAll('.item');
for (let i = 0; i < 1000; i++) {
// Process cachedItems
}

Try Oyxlabs' Proxies & Scraper API

Residential Proxies

Self-Service

Human-like scraping without IP blocking

From

8

Datacenter Proxies

Self-Service

Fast and reliable proxies for cost-efficient scraping

From

1.2

Web scraper API

Self-Service

Public data delivery from a majority of websites

From

49

Useful resources

Get the latest news from data gathering world

I'm interested