The querySelector()
is a document method that returns the first element that matches the provided CSS selectors. It returns an element object which is the first element in the document that matches the specified selectors. If there is no match found then it returns null
.
Select tags using querySelector()
We can directly specify the tag name in the querySelector() to select the HTML tags. Let’s select the title
tag from the below HTML.
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>Test Page</h1>
</body>
</html>
//app.js
let title = document.querySelector('title');
console.log(title); // <title>Sample Page</title>
console.log(title.innerText); // Sample Page
Similarly,
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>Test Page</h1>
<span>This is a Span</span>
</body>
</html>
To select the span,
document.querySelector('span'); // <span>This is a Span</span>
Select id using querySelector()
We can use the #
id selector to select the id element in the querySelector(). For example,
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h1>Test Page</h1>
<div id="container">Container</div>
</body>
</html>
To select the element with id container
, you can write
document.querySelector('#container');
Select class using querySelector()
We can use the .
class selector to select the class element in the querySelector(). For example,
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h1>Test Page</h1>
<div class="container">Container</div>
</body>
</html>
To select the element with class container
, you can write
document.querySelector('.container');
Select child elements using querySelector
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h1>Test Page</h1>
<div class="container">
<span>Span</span>
</div>
</body>
</html>
To select the child element span
with the parent div
, we can write
document.querySelector('div>span');