querySelector()

MamtaWardhani's avatar
Published Mar 21, 2025
Contribute to Docs

The querySelector() method returns the first element within the document that matches a specified CSS selector. It efficiently searches the DOM (Document Object Model) and provides a modern approach to selecting elements in JavaScript. Unlike older methods, querySelector() supports all CSS selector syntax, making it a powerful and flexible tool for DOM manipulation.

querySelector() is commonly used in web development to access and modify DOM elements for creating dynamic and interactive web applications. It simplifies the process of targeting specific elements based on their tags, classes, IDs, or other attributes without needing multiple selection methods.

Syntax

document.querySelector(selectors);

Parameters:

  • selectors: A string containing one or more CSS selectors separated by commas. This parameter is required and must follow standard CSS syntax rules.

Return value:

The querySelector() method returns the first element within the document that matches the specified selector, or null if no matches are found.

querySelector() Vs. querySelectorAll()

The querySelector() and querySelectorAll() methods are both used to select elements from the DOM, but they have key differences:

  • querySelector() returns the first matching element based on the specified CSS selector.
  • querySelectorAll() returns a NodeList of all matching elements that fit the given CSS selector.

To know more about querySelectorAll(), refer to its detailed entry - querySelectorAll().

Example 1: Selecting Elements with Class Names

This example demonstrates how to use querySelector to select an element by its class name:

<!DOCTYPE html>
<html>
<head>
<title>querySelector Class Example</title>
</head>
<body>
<div class="container">
<p class="highlight">This is a highlighted paragraph.</p>
<p>This is a normal paragraph.</p>
</div>
<script>
// Select the first element with class "highlight"
const highlightedElement = document.querySelector('.highlight');
// Change the text color of the selected element
highlightedElement.style.color = 'red';
// Log the element to the console
console.log(highlightedElement);
</script>
</body>
</html>

The output for this example is as follows:

A webpage displaying a paragraph with red-colored text, highlighting the use of querySelector to change styles

This example selects the first paragraph with the class "highlight" and changes its text color to red. The querySelector() method uses the CSS class selector syntax (preceded by a dot) to target elements with specific classes.

Example 2: Selecting Elements with Complex Selectors

This example showcases the power of querySelector() with more complex selectors:

<!DOCTYPE html>
<html>
<head>
<title>querySelector Complex Selectors</title>
<style>
.active {
background-color: yellow;
}
</style>
</head>
<body>
<div id="user-panel">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button class="login-button">Login</button>
</div>
<div id="content">
<ul class="menu">
<li class="active">Home</li>
<li>Products</li>
<li>About</li>
</ul>
</div>
<script>
// Select the password input field
const passwordField = document.querySelector(
'#user-panel input[type="password"]'
);
// Add a border to the password field
passwordField.style.border = '2px solid blue';
// Select the active menu item
const activeMenuItem = document.querySelector('.menu .active');
// Add some padding to the active menu item
activeMenuItem.style.padding = '10px';
console.log('Password field:', passwordField);
console.log('Active menu item:', activeMenuItem);
</script>
</body>
</html>

The output generated by this example is as follows:

A webpage showing a password field with a blue border and a menu with a highlighted 'Home' item, demonstrating complex selectors in querySelector

This example demonstrates using descendent selectors and attribute selectors to precisely target specific elements in a more complex DOM structure. The first selector targets an input with type="password" within the #user-panel element, while the second selector finds an element with class "active" within an element with class "menu".

Example 3: Dynamic Content Manipulation with querySelector

This example shows how querySelector() can be used to dynamically update content based on user interaction:

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content with querySelector</title>
<style>
.hidden {
display: none;
}
.visible {
display: block;
}
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div id="app">
<h1 id="title">Welcome to Our Website</h1>
<div class="tabs">
<button class="tab-button active" data-tab="tab1">Tab 1</button>
<button class="tab-button" data-tab="tab2">Tab 2</button>
<button class="tab-button" data-tab="tab3">Tab 3</button>
</div>
<div class="tab-content visible" id="tab1">
<p>This is the content for Tab 1.</p>
</div>
<div class="tab-content hidden" id="tab2">
<p>This is the content for Tab 2.</p>
</div>
<div class="tab-content hidden" id="tab3">
<p>This is the content for Tab 3.</p>
</div>
</div>
<script>
// Get all tab buttons
const tabButtons = document.querySelectorAll('.tab-button');
// Add click event listeners to each button
tabButtons.forEach((button) => {
button.addEventListener('click', function () {
// Remove 'active' class from all buttons
document
.querySelector('.tab-button.active')
.classList.remove('active');
// Add 'active' class to clicked button
this.classList.add('active');
// Hide all tab content
const allTabContent = document.querySelectorAll('.tab-content');
allTabContent.forEach((tab) => {
tab.classList.add('hidden');
tab.classList.remove('visible');
});
// Show selected tab content
const tabToShow = this.getAttribute('data-tab');
const selectedTab = document.querySelector(`#${tabToShow}`);
selectedTab.classList.remove('hidden');
selectedTab.classList.add('visible');
// Update the page title
const title = document.querySelector('#title');
title.textContent = `You are viewing ${tabToShow}`;
title.classList.add('highlight');
// Remove highlight after 1 second
setTimeout(() => {
title.classList.remove('highlight');
}, 1000);
});
});
</script>
</body>
</html>

The output generated by this example is as follows:

A tabbed interface where clicking different tabs updates the content and highlights the selected tab dynamically using querySelector

This example demonstrates creating a tabbed interface using querySelector() and querySelectorAll(). When a user clicks on a tab button, the code uses querySelector() to find the active tab, update its class, and show the corresponding content. This practical application showcases how querySelector() enables dynamic content manipulation based on user interaction.

To explore more about the DOM and how to manipulate it using jQuery, check out Learn jQuery: DOM Traversing course on Codecademy.

All contributors

Contribute to Docs

Learn JavaScript on Codecademy