Query Multiple Elements Natively Without jQuery
Modern web development no longer requires jQuery to select and
manipulate multiple DOM elements simultaneously. Native JavaScript
provides robust, built-in methods—primarily
document.querySelectorAll(), alongside legacy methods like
document.getElementsByClassName() and
document.getElementsByTagName()—that offer equal or
superior performance to the jQuery $() function without the
overhead of an external library.
Using
document.querySelectorAll()
The most versatile and direct alternative to jQuery’s
$() selector is document.querySelectorAll().
It accepts any valid CSS selector string (classes, IDs, attributes, or
pseudo-classes) and returns a static NodeList containing
all matching elements.
// Select all elements with the class 'card'
const cards = document.querySelectorAll('.card');
// Select all buttons inside a specific container
const buttons = document.querySelectorAll('#container button');Unlike older native methods, a NodeList includes a
built-in .forEach() method, allowing you to iterate over
elements immediately:
document.querySelectorAll('.item').forEach((element) => {
element.classList.add('active');
});To use array methods like .map(),
.filter(), or .reduce(), you can convert the
NodeList into a standard JavaScript array using the spread
operator or Array.from():
const itemsArray = [...document.querySelectorAll('.item')];Using
document.getElementsByClassName()
If you only need to select elements by class name,
document.getElementsByClassName() is an alternative that
performs faster than querySelectorAll(). It returns a live
HTMLCollection, which updates automatically if matching
elements are added or removed from the DOM.
const alerts = document.getElementsByClassName('alert');Because an HTMLCollection does not have a native
.forEach() method, you must convert it to an array or use a
standard for loop to iterate through it:
const alerts = document.getElementsByClassName('alert');
Array.from(alerts).forEach((alert) => {
alert.style.display = 'none';
});Using
document.getElementsByTagName()
To select elements by their HTML tag name, such as all paragraphs or
list items, use document.getElementsByTagName(). Like
getElementsByClassName(), this method returns a live
HTMLCollection.
const paragraphs = document.getElementsByTagName('p');
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.lineHeight = '1.5';
}Scoped Element Selection
Native methods are not limited to the global document
object. You can scope your query to a specific parent element to improve
performance and target specific components:
const modal = document.querySelector('#modal');
const modalInputs = modal.querySelectorAll('input');For general use, document.querySelectorAll() serves as
the standard replacement for jQuery's multiple-element selector,
offering full CSS selector compatibility across all modern browsers.