How to query select an element in JavaScript
Selecting specific HTML elements with CSS selector syntax is essential for modern JavaScript DOM manipulation and event handling.
As the creator of CoreUI with over 25 years of software development experience, I’ve relied on querySelector() extensively to build precise component interactions and dynamic UI behaviors.
The most effective approach is using querySelector() for single elements or querySelectorAll() for multiple elements, both supporting the full CSS selector specification.
These methods provide powerful, flexible element selection that works consistently across all modern browsers.
Use querySelector() with CSS selector syntax to select the first matching element in the document.
const button = document.querySelector('.btn-primary')
const firstInput = document.querySelector('input[type="email"]')
const navItem = document.querySelector('#navbar .nav-item:first-child')
// Add event listener to selected element
button.addEventListener('click', () => {
console.log('Button clicked!')
})
The querySelector() method accepts any valid CSS selector string and returns the first element that matches the criteria, or null if no match is found. You can use class selectors (.class), ID selectors (#id), attribute selectors ([type="text"]), pseudo-selectors (:first-child), and complex combinations. This provides the same targeting power as CSS with the flexibility to select elements by any combination of attributes, position, or hierarchy.
Best Practice Note:
This is the primary method we use in CoreUI for element selection due to its CSS selector compatibility and precise targeting capabilities.
Always check if the returned element exists before manipulating it, since querySelector() returns null when no element matches the selector.



