ZetCode

JavaScript querySelector

last modified April 2, 2025

In this article, we explore the document.querySelector method in JavaScript. This powerful method allows developers to select DOM elements using CSS selectors, providing flexible element selection capabilities.

Basic Definition

The document.querySelector method returns the first element that matches a specified CSS selector or group of selectors. It searches the entire document and returns only the first matching element.

Unlike getElementById, querySelector can use any CSS selector, including classes, attributes, pseudo-classes, and complex selectors. This makes it much more versatile for DOM manipulation tasks.

Basic querySelector

This example demonstrates how to select an element by its class using querySelector.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic querySelector</title>
</head>
<body>

<div class="content">Hello there!</div>

<script>
    const element = document.querySelector('.content');
    console.log(element.textContent);
</script>

</body>
</html>

In this basic example, we have a div element with the class "content". The JavaScript code retrieves this element using querySelector with the class selector (.) and logs its text content to the console.

This demonstrates the fundamental usage of querySelector to access elements by their CSS selectors. The method returns the first matching element, which we can then manipulate as needed.

Selecting by ID

This example shows how to use querySelector to select an element by its ID, similar to getElementById.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Selecting by ID</title>
</head>
<body>

<h1 id="main-heading">Welcome to our site</h1>

<script>
    const heading = document.querySelector('#main-heading');
    heading.style.color = 'blue';
    heading.style.fontSize = '2.5rem';
</script>

</body>
</html>

Here we select an h1 element by its ID using the ID selector (#). We then modify its style properties directly through JavaScript.

While this achieves similar results to getElementById, querySelector provides a more consistent way to select elements using CSS selector syntax throughout your code.

Complex Selectors

This example demonstrates how to use complex CSS selectors with querySelector.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Complex Selectors</title>
</head>
<body>

<ul class="menu">
    <li>Home</li>
    <li class="active">Products</li>
    <li>About</li>
</ul>

<script>
    const activeItem = document.querySelector('ul.menu li.active');
    activeItem.style.fontWeight = 'bold';
    activeItem.style.color = 'green';
</script>

</body>
</html>

In this example, we use a descendant selector combined with a class selector to target a specific list item within a menu. The selector 'ul.menu li.active' finds the li element with class "active" that is a descendant of a ul element with class "menu".

This shows the power of querySelector in targeting specific elements within complex DOM structures using familiar CSS selector syntax.

Attribute Selectors

This example demonstrates how to use attribute selectors with querySelector.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Attribute Selectors</title>
</head>
<body>

<input type="text" placeholder="Enter your email" data-required="true">
<button onclick="validateInput()">Validate</button>

<script>
    function validateInput() {
        const input = document.querySelector('input[data-required="true"]');
        if (!input.value) {
            input.style.border = '2px solid red';
        } else {
            input.style.border = '';
        }
    }
</script>

</body>
</html>

Here we use an attribute selector to find an input element with a specific data attribute. The selector 'input[data-required="true"]' matches any input element that has a data-required attribute with value "true".

This demonstrates how querySelector can be used with custom data attributes to create more semantic and maintainable JavaScript code.

Pseudo-class Selectors

This example shows how to use pseudo-class selectors with querySelector.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Pseudo-class Selectors</title>
</head>
<body>

<ul class="links">
    <li><a href="#">First link</a></li>
    <li><a href="#">Second link</a></li>
    <li><a href="#">Third link</a></li>
</ul>

<script>
    const firstLink = document.querySelector('.links li:first-child a');
    firstLink.style.color = 'purple';
    firstLink.style.textDecoration = 'none';
</script>

</body>
</html>

In this example, we use the :first-child pseudo-class to select the first anchor element within our list. The selector '.links li:first-child a' targets the a element that is a child of the first li element within an element with class "links".

This demonstrates how querySelector can leverage CSS pseudo-classes to select elements based on their position or state in the document.

Source

MDN querySelector Documentation

In this article, we have shown how to use document.querySelector in JavaScript. This method provides powerful element selection capabilities using CSS selector syntax, making it essential for modern web development.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all JS DOM tutorials.