Home >Web Front-end >JS Tutorial >Mastering querySelector and querySelectorAll in JavaScript
The querySelector and querySelectorAll methods are powerful tools in JavaScript for selecting elements in the DOM. They allow developers to use CSS selectors to identify and manipulate HTML elements.
The querySelector method selects the first element that matches the specified CSS selector.
document.querySelector(selector);
<div> <pre class="brush:php;toolbar:false">const firstText = document.querySelector(".text"); console.log(firstText.textContent); // Output: First paragraph
The querySelectorAll method selects all elements that match the specified CSS selector and returns them as a NodeList.
document.querySelectorAll(selector);
const allTexts = document.querySelectorAll(".text"); allTexts.forEach((text) => console.log(text.textContent)); // Output: // First paragraph // Second paragraph
const secondText = allTexts[1]; console.log(secondText.textContent); // Output: Second paragraph
Feature | querySelector | querySelectorAll | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
First matching element | All matching elements | |||||||||||||||
Return Type | Single DOM element | NodeList (array-like structure) | |||||||||||||||
Iteration | Not iterable | Iterable (e.g., using forEach) | |||||||||||||||
Use Case | When one element is needed | When multiple elements are needed |
You can combine CSS selectors for more specific queries.
document.querySelector(selector);
<div> <pre class="brush:php;toolbar:false">const firstText = document.querySelector(".text"); console.log(firstText.textContent); // Output: First paragraph
document.querySelectorAll(selector);
const allTexts = document.querySelectorAll(".text"); allTexts.forEach((text) => console.log(text.textContent)); // Output: // First paragraph // Second paragraph
const secondText = allTexts[1]; console.log(secondText.textContent); // Output: Second paragraph
const containerParagraph = document.querySelector("#container .text"); console.log(containerParagraph.textContent); // Output: First paragraph
Since querySelectorAll returns a NodeList, you can loop through it using forEach, for...of, or indexing.
const header = document.querySelector("#header");
const buttons = document.querySelectorAll(".button");
If no matching elements are found:
const paragraphs = document.querySelectorAll("p");
Mastering these methods will make your JavaScript code cleaner and more efficient!
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
The above is the detailed content of Mastering querySelector and querySelectorAll in JavaScript. For more information, please follow other related articles on the PHP Chinese website!