By the end of this lesson, you will understand how to select elements using querySelector in JavaScript. This method simplifies your task by allowing easy access to HTML elements.
The querySelector method enables you to access HTML elements quickly. It finds and selects the first matching element based on a CSS selector. For example, if your webpage has a button and you want to change its style, you can use querySelector to select that button. Therefore, knowing how to use this method is crucial for effective web development.
Here’s a brief overview of how to use querySelector efficiently. This method selects only the first instance it encounters. If you need to select multiple elements, you should opt for querySelectorAll. The difference is essential, as querySelectorAll provides a list of elements, while querySelector returns just the first one.
File: select-element.php
<!DOCTYPE html>
<html>
<head>
<title>Select Element Example</title>
<style>
.highlight { color: red; font-weight: bold; }
</style>
</head>
<body>
<h1 id="header">Hello, World!</h1>
<button id="myButton">Click Me!</button>
<script>
const button = document.querySelector('#myButton');
button.addEventListener('click', function() {
const header = document.querySelector('#header');
header.classList.add('highlight');
});
</script>
</body>
</html>
Expected output: When clicking the button, the header text "Hello, World!" will change to red and bold.
In the example above, we select a button and add an event listener to it. When a user clicks the button, we utilize querySelector once more to select the header. Then, we apply the class highlight to modify its style. The line const button = document.querySelector('#myButton'); selects the button, while const header = document.querySelector('#header'); selects the header. Consequently, when the button is clicked, the event listener triggers, adding interactivity to your webpage.
Try to add a new paragraph below the button. When the button is clicked, change the text of that paragraph to “Button Clicked!” Use querySelector to select the paragraph. This activity will help strengthen your understanding of selecting elements with this method.
<!DOCTYPE html>
<html>
<head>
<title>Select Element Task</title>
</head>
<body>
<h1 id="header">Hello, World!</h1>
<button id="myButton">Click Me!</button>
<p id="myParagraph">Waiting for click...</p>
<script>
const button = document.querySelector('#myButton');
button.addEventListener('click', function() {
const paragraph = document.querySelector('#myParagraph');
paragraph.textContent = 'Button Clicked!';
});
</script>
</body>
</html>
querySelector for easy element selection.Understanding how to select elements using querySelector improves your JavaScript skills. If you want to explore JavaScript fundamentals further, check out this lesson. Remember, practice is essential!