Query Selector
Query selectors are methods used to find and select HTML elements from the DOM using CSS-style selectors. They provide a powerful way to target elements without needing IDs or complex traversal.
Methods
javascript// Select first matching element const element = document.querySelector('.class-name') // Select all matching elements const elements = document.querySelectorAll('.class-name')
CSS Selector Syntax
javascript// By class document.querySelector('.button') // By ID document.querySelector('#header') // By tag document.querySelector('div') // By attribute document.querySelector('[data-id="123"]') // Complex selectors document.querySelector('nav ul li:first-child') // Multiple selectors document.querySelector('.active, .selected') // Nested selectors document.querySelector('.container > .item')
Common Use Cases
javascript// Find and modify element const button = document.querySelector('.submit-btn') button.textContent = 'Click Here' // Find multiple elements const items = document.querySelectorAll('.list-item') items.forEach(item => { item.classList.add('active') }) // Check if element exists const modal = document.querySelector('.modal') if (modal) { modal.style.display = 'block' }
Advantages
- Uses familiar CSS selector syntax
- More powerful than
getElementByIdorgetElementsByClassName - Works with any CSS selector
- Returns standard element objects
querySelector vs querySelectorAll
querySelector
- Returns first match only
- Returns single element or null
- Stops searching after first match
querySelectorAll
- Returns all matches
- Returns NodeList (array-like)
- Searches entire document