Selecting Elements with querySelector
Find elements using CSS selectors.
Meet querySelector
querySelector returns the first element that matches a CSS selector, or null if nothing matches. It lives on document and on every element.
const title = document.querySelector("h1");
console.log(title.textContent);Any CSS Selector Works
The power of querySelector is that it accepts the same selectors you use in CSS: tags, classes, ids, attributes, and combinations.
document.querySelector("#main"); // by id
document.querySelector(".card"); // by class
document.querySelector("input[type=email]"); // by attributeAll lessons in this course
- Selecting Elements with querySelector
- getElementById and getElementsByClassName
- Traversing Parents, Children and Siblings
- NodeList vs HTMLCollection