Combining Selectors Effectively
What you'll learn: How to use CSS selector syntax within querySelector() and querySelectorAll() to pinpoint exactly the elements you need.
The Power of CSS Selectors in JavaScript
Now that you know querySelector() and querySelectorAll(), you can leverage the full power of CSS selector syntax to find elements with surgical precision. Instead of grabbing everything with a class and filtering later, you can combine selectors—just like in CSS—to target exactly what you want in one line.
Combining Multiple Selectors
You can chain selectors together without spaces to target elements that match all criteria:
document.querySelector('div.warning')— a<div>that has the class "warning"document.querySelector('button#submit.active')— a button with ID "submit" and class "active"
You can also use descendant selectors (with spaces) to find elements inside other elements:
document.querySelectorAll('nav a')— all links inside a<nav>document.querySelector('.container .button')— elements with class "button" inside elements with class "container"
Attribute Selectors
Target elements based on their attributes:
document.querySelectorAll('[type="checkbox"]')— all checkbox inputsdocument.querySelector('a[href^="https"]')— links starting with "https"
Pseudo-Class Selectors
Use pseudo-classes to select elements in specific states:
document.querySelector('input:focus')— the currently focused inputdocument.querySelectorAll('li:first-child')— first child of every listdocument.querySelector('button:disabled')— disabled buttons
Think of combining selectors like giving increasingly specific directions: instead of saying "find all buttons," you're saying "find the disabled submit button inside the checkout form."
Key Takeaway: Combining CSS selectors with querySelector() lets you write precise, powerful selection statements that grab exactly the elements you need without extra filtering code.