Query Selectors in JavaScript
From the DOM Manipulation cheat sheet · Element Selection · verified Jul 2026
Query Selectors
Select elements using CSS selectors for flexible element targeting
javascript
// Select first matching element
const element = document.querySelector('.class-name')
const element = document.querySelector('#id')
const element = document.querySelector('[data-id="123"]')
// Select all matching elements (returns NodeList)
const elements = document.querySelectorAll('.class-name')
const elements = document.querySelectorAll('div.active')
const elements = document.querySelectorAll('[type="checkbox"]:checked')
// Convert NodeList to Array
const array = Array.from(document.querySelectorAll('.item'))
const array = [...document.querySelectorAll('.item')]💡 querySelector uses CSS selector syntax
⚡ getElementById is faster for IDs
📌 querySelectorAll returns NodeList, not Array
✅ Always check if element exists before using