Concept Explanation
Before you can change a button, you have to "Find" it. In the old days, we used specifically named methods like getElementById.
Modern JavaScript uses querySelector. It uses the exact same syntax as CSS, making it the most powerful and flexible way to target elements.
Syntax or Core Structure
The Big Two
// 1. Selector for ONE element (First match)
const submitBtn = document.querySelector("#submit-user");
// 2. Selector for ALL elements (Returns a NodeList)
const allGradients = document.querySelectorAll(".glass-card");
Old School (Still useful for performance)
const element = document.getElementById("main-header");
const items = document.getElementsByClassName("list-item");
Common Mistakes
- Forgot the Symbol: Typing
querySelector("my-id")instead ofquerySelector("#my-id"). Remember:#for ID,.for Class! - NodeList is not an Array:
querySelectorAllreturns a NodeList. You can use.forEach()on it, but you cannot use.map()or.filter()unless you turn it into a real array first:[...myNodeList]. - Null Selector: If you try to select an element that doesn't exist, JS returns
null. If you then try to doelement.style, your app will crash! Always check if the element exists first.
Best Practices
- Use ID for Unique Items: Use
#idfor things that appear only once (like a logo or main nav). - Use Data Attributes: Instead of selecting by CSS classes (which change for styling), select by data attributes (
[data-test-id="submit"]) to make your JS more stable. - Cache your Selectors: Don't run
querySelectorinside a loop! Find the element once, save it to a variable, and reuse it.
Practice Exercises
- The Class Hunter: Select all elements with the class "active" and log their count.
- The Tag Tracker: Find the first
<h1>on the page and change its color to "RoyalBlue". - The Attribute Finder: Select an input field by its
nameattribute usingquerySelector.