The querySelector() method returns the first element that matches the specified Selector. It only gives one element from the HTML DOM if found else it returns null. To get all the matching elements, you can use the querySelectorAll() method.
Syntax
// To search in complete documemt
ducument.querySelector(selectors);
// To search inside a specific element
element.querySelector("html-tag .class-name #element-id...");
selectors: It is a string containing the CSS Selectors.
Return value: The first element that matches the selectors if found else null.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<body style="text-align: center">
<p>This is paragraph 1.</p>
<p>This is paragraph 2.</p>
<button onclick="myFunction()">Try it</button>
<!--Driver Code Ends-->
<script>
function myFunction() {
// Select the first p element
let e = document.querySelector("p");
// Dynamically apply styling
// to the first p element
e.style.backgroundColor = "Green";
e.style.color = "white";
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- Uses full CSS selector power : You can use any valid CSS selector (classes, IDs, attributes, pseudo-classes, combinators, etc.), making it far more flexible than older methods like getElementById() or getElementsByClassName().
- Returns only the first match : Unlike querySelectorAll(), which returns all matching elements, querySelector() stops at the first one it finds (using depth-first order).