Learn everything about QuerySelector in JavaScript, from its definition to practical examples tailored for an 18-year-old audience. Master DOM manipulation today!
The querySelector
method is a function in JavaScript used to select DOM elements based on CSS selectors. This means you can grab any element in your HTML by specifying a selector, and it works for a single element.
document.querySelector('.myClass')
will select the first element with the class myClass
.div
with an ID of header
, you'd write document.querySelector('#header')
.querySelector
will only return the first matching element in the DOM. If you need all matches, you would use querySelectorAll
.Let's look at an example to understand how it works in practice:
<!DOCTYPE html>
<html>
<head>
<title>QuerySelector Example</title>
</head>
<body>
<div id='header'>Header Section</div>
<p class='description'>This is a paragraph.</p>
<script>
// Selecting the header div
const header = document.querySelector('#header');
header.style.backgroundColor = 'lightblue'; // Changing its background color
// Selecting the first paragraph with the class 'description'
const description = document.querySelector('.description');
description.style.fontSize = '20px'; // Changing font size
</script>
</body>
</html>
In the above example, we select a div
with an ID of header
and a p
with a class of description
. We then apply a style change to both elements, demonstrating how querySelector
works in practice.
querySelector
returns the first matching element.querySelectorAll
.By understanding and using querySelector
, you can effectively manipulate your web pages and create dynamic interactions with users.