document.querySelector
is a JavaScript function that allows you to select the first matching element in the document by providing a CSS selector. This function returns the matching element if a match was found, otherwise null
. document.querySelector
is a very useful method because it allows you to easily select and manipulate DOM elements with various selectors.
The usage of the function is as follows:
const element = document.querySelector(selector);
where selector
is a string containing CSS selectors for finding and selecting elements.
Here are some document.querySelector
examples using :
-
Select elements by tag name:
const firstParagraph = document.querySelector('p');
This will select the first element in the document
<p>
. -
Select elements by class name:
const firstElementWithClass = document.querySelector('.my-class');
This will select
my-class
the first element in the document with the class name. -
Select elements by ID:
const elementWithId = document.querySelector('#my-id');
This will select
my-id
the element with the ID. -
Select elements via attribute selectors:
const firstInputElement = document.querySelector('input[type="text"]');
This will select the first element of type in the
text
document<input>
. -
Select elements with compound selectors:
const firstElement = document.querySelector('.my-class.another-class');
This will select the first element in the document with the
my-class
and class names.another-class
Note that document.querySelector
only the first matching element is returned. If you want to select all matching elements in the document, you can use document.querySelectorAll
the function. This function returns a NodeList containing all matching elements.
const allElementsWithClass = document.querySelectorAll('.my-class');