querySelector()
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 elementhighlightedElement.style.color = 'red';// Log the element to the consoleconsole.log(highlightedElement);</script></body></html>
The output for this example is as follows:
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 fieldconst passwordField = document.querySelector('#user-panel input[type="password"]');// Add a border to the password fieldpasswordField.style.border = '2px solid blue';// Select the active menu itemconst activeMenuItem = document.querySelector('.menu .active');// Add some padding to the active menu itemactiveMenuItem.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:
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 buttonsconst tabButtons = document.querySelectorAll('.tab-button');// Add click event listeners to each buttontabButtons.forEach((button) => {button.addEventListener('click', function () {// Remove 'active' class from all buttonsdocument.querySelector('.tab-button.active').classList.remove('active');// Add 'active' class to clicked buttonthis.classList.add('active');// Hide all tab contentconst allTabContent = document.querySelectorAll('.tab-content');allTabContent.forEach((tab) => {tab.classList.add('hidden');tab.classList.remove('visible');});// Show selected tab contentconst tabToShow = this.getAttribute('data-tab');const selectedTab = document.querySelector(`#${tabToShow}`);selectedTab.classList.remove('hidden');selectedTab.classList.add('visible');// Update the page titleconst title = document.querySelector('#title');title.textContent = `You are viewing ${tabToShow}`;title.classList.add('highlight');// Remove highlight after 1 secondsetTimeout(() => {title.classList.remove('highlight');}, 1000);});});</script></body></html>
The output generated by this example is as follows:
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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours