CSS Selectors in JavaScript
CSS Selectors in JavaScript
querySelector uses CSS selector syntax - the same selectors you use in CSS!
Selector Types
By ID (use #)
document.querySelector("#header");
// Selects: <div id="header">
By Class (use .)
document.querySelector(".menu");
// Selects: <nav class="menu">
By Tag (just the name)
document.querySelector("button");
// Selects: <button>
Combined Selectors
// Element with specific class
document.querySelector("div.container");
// Element inside another
document.querySelector(".menu .item");
// Direct child
document.querySelector(".list > li");
// By attribute
document.querySelector("[type='submit']");
document.querySelector("[data-id='123']");
CSS Selector Cheat Sheet
| Selector | Meaning | Example |
|---|---|---|
#id | ID | #header |
.class | Class | .menu |
tag | Element | button |
A B | B inside A | .menu a |
A > B | B direct child of A | .list > li |
[attr] | Has attribute | [disabled] |
[attr='val'] | Attribute equals | [type='text'] |
Your Turn!
Create a function that selects an element by class name (add the "." prefix).