What is querySelector?

querySelector is one of the powerful DOM (Document Object Model) manipulation features in JavaScript. This method is used to select specific elements from an HTML document using CSS selectors. For example, if you want to find elements that match a specific class, ID, or attribute, you can easily access them using querySelector.

This method is widely used to make dynamic changes to specific parts of a web page or to update page content in response to user actions. For example, you can change text when a button is clicked or modify styles under certain conditions.

The usage of querySelector is very simple and is written in the following format:

const element = document.querySelector('.some-class');

 
This code selects the first element with the class name “some-class” and stores it in the variable element. Since querySelector returns only the first matched element, use querySelectorAll to select multiple elements.

In real-world web development, understanding how to use querySelector is important for writing efficient and flexible code. In this article, we will introduce its basic usage and practical applications through specific examples using querySelector.

Overview of the Demo Page

Here is a common example using JavaScript’s querySelector explained in a demo page format. In this example, we use HTML, CSS, and JavaScript code structured in a way that is easy for beginners to understand.

  • Goal: When the user clicks a button, specific text on the page changes.
  • Technologies: HTML for structure, CSS for styling, and JavaScript for dynamic behavior.

HTML Code

Display a greeting message with the id=”greeting” tag and place a button using the button tag to change the text.

<div id="greeting">Hello, World!</div>
<button id="changeText">Change Text</button>

CSS Code

Apply basic styling to improve the appearance.

<style>
body {
    font-size: 16px;
    text-align: center;
    margin: 0;
}
h1{
    text-align: center;
    font-size: 20px;
    padding: 10px 0 20px 0;
    line-height: 1.8em;
}
#greeting{
    font-size: 24px;
    font-weight: bold;
    color: red;
}
button {
    margin-top: 20px;
    padding: 10px 15px;
    font-size: 16px;
    cursor: pointer;
}
</style>

JavaScript Code

  • After the page loads, use querySelector to get the button element.
  • When the button is clicked, use querySelector again to get the h1 element and change its text content.
<script>
document.addEventListener('DOMContentLoaded', function () {
    const button = document.querySelector('#changeText');
    button.addEventListener('click', function () {
        const greeting = document.querySelector('#greeting');
        greeting.textContent = 'Goodbye, World!';
    });
});
</script>

 
This code demonstrates the basic usage of querySelector, selecting specific elements and adding event listeners to create dynamic behavior.

Demo Page: Changing Text Using querySelector

Open the demo page below to see how text can be changed using querySelector.

Demo Page: Changing Text Using querySelector

Advantages of querySelector

  • Simple and intuitive:
    Elements can be easily found using CSS selectors, making the code more readable.
  • Versatile:
    Supports most CSS selectors (class, ID, attribute selectors, etc.), allowing selection of various elements.
  • Flexible:
    Not only can you select a single element, but you can also select multiple elements using querySelectorAll.

Disadvantages of querySelector

  • Performance issues:
    When used frequently, especially in large DOM structures, it may be slightly slower than other methods (such as getElementById).
  • Compatibility with older browsers:
    It is not supported in older browsers (especially IE8 and below), which may cause compatibility issues.

Important Notes

  • Returns only the first element:
    querySelector returns only the first element that matches the specified selector. If you want to operate on multiple elements, you need to use querySelectorAll.
  • Be careful with dynamically added elements:
    You may not be able to directly access elements that are dynamically added after the page loads using querySelector. In such cases, you need to run the query again after the DOM updates or use event delegation.

Summary

querySelector is a very useful tool in modern web development. With its intuitive usage and strong support for CSS selectors, developers can quickly and effectively manipulate DOM elements. However, from the perspective of older browser support and performance, there are some trade-offs to consider when using it. As shown in the demo example above, querySelector is a highly effective option for simple operations, but in more complex scenarios, choosing the appropriate tool becomes important.

 
*If you reuse this content, please do so at your own responsibility.*
Do not reuse the Google Analytics tag inside the head tag of the demo page.