Definition and Usage
The querySelector()
function returns the first element that matches a specified CSS selector within a Document
or Element
Object.
Returns null
if no match is found.
Basic Example
// Select the first element in the document with the class name ".item"
const firstItem = document.querySelector(".item");
// Select within a specific element
const container = document.getElementById("container");
const nestedButton = container.querySelector("button.primary");
// When no matching element exists
const notExist = document.querySelector(".no-such-class"); // Returns null
Syntax
// Called on the Document object (entire document)
document.querySelector(selectors)
// Called on an Element object (specific element)
element.querySelector(selectors)
Parameters
selectors |
The selector string used to identify the target element.
Must be a valid CSS selector string. If not specified or invalid, a TypeError will be thrown. |
---|
Return value
- When called on a
Document
object (the entire document), it returns the first element that matches the specified CSS selector within the document. - When called on an
Element
object (a specific element), it returns the first element that matches the specified CSS selector within that element. - Returns
null
if no matching element is found.
Note:
If you need a list of all elements matching the specified selector, use the querySelectorAll()
function.
Examples
Let's explore how to use the querySelector()
function through examples.
Finding an Element Within a Specific Container
To find the first <p>
element inside a specific container (in this example, a <div class="container">
), you can write the following:
<div class="container">
<p>This is a descendant element.</p>
</div>
const container = document.querySelector(".container"); // Select the container element
const matched = container.querySelector("p"); // Find the first <p> within the container
/* This returns the same element as document.querySelector(".container p") */
Changing Element Styles
<div id="my-element">This element's style will be changed.</div>
const element = document.querySelector("#my-element");
element.style.backgroundColor = "lightblue";
element.style.color = "darkblue";
In this example, the querySelector()
function is used to select the element with the id
my-element
and then change its background color and text color.
Adding an Event Listener
<button id="my-button">Click Me</button>
const button = document.querySelector("#my-button");
button.addEventListener("click", () => {
alert("Button clicked!");
});
This example selects the button with id
my-button
and adds a click event listener. When the button is clicked, an alert message is displayed.
Dynamically Adding Content
<ul id="my-list"></ul>
const myList = document.querySelector("#my-list");
const items = ["Item 1", "Item 2", "Item 3"];
for (let i = 0; i < items.length; i++) {
let listItem = document.createElement("li");
listItem.textContent = items[i];
myList.appendChild(listItem);
}
Code Explanation
The for
loop repeats a block of code a specific number of times.
Code Explanation
The createElement()
function creates and returns a new HTML element.
Code Explanation
The appendChild()
function adds a node as the last child of a specified parent node.
In this example, querySelector()
selects the list element with the id
my-list
, and JavaScript is used to dynamically add list items. This is a common pattern for generating and inserting content dynamically.
Returning null
When No Match is Found
<!DOCTYPE html>
<html lang="en">
<head>
<title>querySelector() Example</title>
</head>
<body>
<div id="my-element">This element can be selected.</div>
<script>
const nonExistentElement = document.querySelector("#non-existent-element");
if (nonExistentElement === null) {
console.log("No matching element found.");
} else {
console.log("Matching element found.");
}
</script>
</body>
</html>
In this example, since there is no element with the id
non-existent-element
in the document, the querySelector()
call returns null
. The if...else
statement then checks the result and logs an appropriate message to the console. The output will be: No matching element found.
Browser compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
querySelector()
|
1 | 12 | 3.5 | 3.1 |
Specifications
Specification | |
---|---|
querySelector()
|
DOM Standard #ref-for-dom-parentnode-queryselectorâ‘ |