How to query select all elements in JavaScript

Selecting multiple DOM elements simultaneously is crucial for batch operations and efficient page manipulation. With over 25 years of experience in web development and as the creator of CoreUI, I’ve used querySelectorAll extensively in UI components. From my expertise, the most versatile approach is using document.querySelectorAll() which accepts any valid CSS selector and returns a NodeList. This method provides the flexibility to select elements by class, attribute, or complex CSS patterns.

Use document.querySelectorAll() with CSS selectors to select multiple elements at once.

const elements = document.querySelectorAll('.button')

Here document.querySelectorAll('.button') selects all elements with the class ‘button’ and returns a NodeList. The method accepts any valid CSS selector including complex patterns like .container > .item:not(.disabled). The returned NodeList can be iterated using forEach, for…of loops, or converted to an array using Array.from() for additional array methods.

Best Practice Note:

This is the same approach we use in CoreUI components to manage collections of UI elements efficiently. Remember that querySelectorAll returns a static NodeList, so it won’t update if the DOM changes after the query.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team