Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
querySelector()
and querySelectorAll()
are the most flexible of all the DOM selector methods. They accept ID's, classes, tag names, and just about any valid CSS selector.
Further Reading
- Locating DOM elements using selectors
- querySelector() – MDN
- querySelectorAll() – MDN
- CSS selectors – MDN
HTMLCollection and NodeList
CSS Selectors
CSS selectors target the HTML elements on our web pages that we want to style. If you'd like to learn more about CSS selectors, including pseudo-class selectors, review the CSS Selectors course on Treehouse.
Example Selectors
Descendant selector
The following targets all anchor tags that are nested inside a nav
element.
const navigationLinks = document.querySelectorAll('nav a');
Attribute selector
The following targets an input element that's: <input type="submit">
. Input elements of type submit
are rendered as buttons.
const btnSubmit = document.querySelector("input[type='submit']");
Pseudo-class
The following selects the "odd" <li>
elements in a list: 1, 3, 5, etc.
const itemsOdd = document.querySelectorAll("li:nth-child(odd)");
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up