JavaScript DOM querySelector and querySelectorAll
querySelector
and querySelectorAll
are powerful methods for selecting elements in the DOM using CSS selectors. They offer more flexibility than methods like getElementById
and getElementsByClassName
, as they can target elements with a variety of selectors.
querySelector
Syntax
const element = document.querySelector(selector);
Parameters
selector
: A string representing a CSS selector used to match elements. This can be any valid CSS selector, including class names, IDs, attribute selectors, pseudo-classes, and combinators.
Return Value
- Returns the first element that matches the specified CSS selector.
- Returns
null
if no matching element is found.
Usage
Selecting Single Elements
<!DOCTYPE html> <html> <head> <title>querySelector Example</title> </head> <body> <div id="container"> <p class="text">Paragraph 1</p> <p class="text">Paragraph 2</p> </div> <button onclick="highlightFirst()">Highlight First Paragraph</button> <script> function highlightFirst() { // Select the first <p> element with class 'text' const firstParagraph = document.querySelector('.text'); // Change its background color firstParagraph.style.backgroundColor = 'yellow'; } </script> </body> </html>
In this example, clicking the button highlights the first
<p>
element with the classtext
.Using Complex Selectors
// Select an element with the ID 'container' and its first child <p> element const firstParagraph = document.querySelector('#container > p');
This selects the first
<p>
element that is a direct child of the element with IDcontainer
.
querySelectorAll
Syntax
const elements = document.querySelectorAll(selector);
Parameters
selector
: A string representing a CSS selector used to match elements. This can include complex selectors and combinators.
Return Value
- Returns a static
NodeList
of all elements that match the specified CSS selector. Unlike theHTMLCollection
returned bygetElementsByClassName
, theNodeList
returned byquerySelectorAll
is not live; it does not automatically update when the DOM changes.
Usage
Selecting Multiple Elements
<!DOCTYPE html> <html> <head> <title>querySelectorAll Example</title> </head> <body> <div id="container"> <p class="text">Paragraph 1</p> <p class="text">Paragraph 2</p> <p class="text">Paragraph 3</p> </div> <button onclick="highlightAll()">Highlight All Paragraphs</button> <script> function highlightAll() { // Select all <p> elements with class 'text' const paragraphs = document.querySelectorAll('.text'); // Loop through the NodeList and change background color paragraphs.forEach(paragraph => { paragraph.style.backgroundColor = 'yellow'; }); } </script> </body> </html>
In this example, clicking the button highlights all
<p>
elements with the classtext
.Using Complex Selectors
// Select all <p> elements within an element with the ID 'container' const paragraphs = document.querySelectorAll('#container p');
This selects all
<p>
elements that are descendants of the element with IDcontainer
.
Comparison
querySelector
: Returns the first matching element and is useful when you only need to access a single element.querySelectorAll
: Returns a staticNodeList
of all matching elements and is useful for accessing multiple elements.
Best Practices
- Use
querySelector
for Single Elements: When you only need to interact with one element,querySelector
is more straightforward. - Use
querySelectorAll
for Multiple Elements: When dealing with multiple elements, usequerySelectorAll
and iterate over theNodeList
withforEach
or a loop. - Complex Selectors: Leverage the power of CSS selectors to target elements precisely.