0
0
JavascriptHow-ToBeginner · 3 min read

How to Use querySelector in JavaScript: Simple Guide

Use document.querySelector(selector) to select the first HTML element that matches the CSS selector. It returns the element or null if no match is found.
📐

Syntax

The querySelector method takes a single string argument called selector, which is a CSS selector used to find elements in the document.

  • document: The web page's document object.
  • querySelector(selector): Finds the first element matching the selector.
  • selector: A CSS selector string like ".class", "#id", or "tag".
javascript
const element = document.querySelector('selector');
💻

Example

This example shows how to select an element by its class name and change its text content.

javascript
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>querySelector Example</title>
</head>
<body>
  <p class="greeting">Hello!</p>
  <script>
    const greetingElement = document.querySelector('.greeting');
    greetingElement.textContent = 'Hello, JavaScript!';
    console.log(greetingElement.textContent);
  </script>
</body>
</html>
Output
Hello, JavaScript!
⚠️

Common Pitfalls

Common mistakes when using querySelector include:

  • Using an incorrect selector string that does not match any element, resulting in null.
  • Trying to use querySelector to select multiple elements (it only returns the first match).
  • Not checking if the returned element is null before accessing its properties.

Always verify the selector and handle the case when no element is found.

javascript
/* Wrong: No element with this selector */
const noElement = document.querySelector('.missing');
// Accessing property without check causes error
// console.log(noElement.textContent); // Error: cannot read property 'textContent' of null

/* Right: Check before using */
if (noElement) {
  console.log(noElement.textContent);
} else {
  console.log('Element not found');
}
Output
Element not found
📊

Quick Reference

UsageDescription
document.querySelector('selector')Selects the first element matching the CSS selector
'.class'Select element by class name
'#id'Select element by ID
'tag'Select element by tag name
nullReturned if no element matches the selector

Key Takeaways

Use document.querySelector with a CSS selector string to get the first matching element.
querySelector returns null if no element matches, so always check before using the result.
It only selects one element; use querySelectorAll to select multiple elements.
Selectors can be any valid CSS selector like classes, IDs, or tags.
Changing element properties after selection updates the page content dynamically.