Table of Contents

The JavaScript querySelector() method lets you select the first element that matches a CSS selector. It is one of the most flexible DOM selection methods because you can use familiar CSS selectors such as IDs, classes, element names, attributes, and combinations of selectors.

1. What Is querySelector() in JavaScript?

querySelector() is a method of the Document and Element interfaces. It searches the relevant DOM subtree and returns the first element that matches the supplied CSS selector. If no element matches, it returns null.

Unlike methods such as getElementById() or getElementsByClassName(), querySelector() accepts CSS selector syntax, making it useful for many different selection tasks.

2. Syntax of querySelector()

document.querySelector(selectors);

// Search only inside a particular element
parentElement.querySelector(selectors);

Parameter: selectors is a string containing one or more valid CSS selectors. Separate selector groups with commas.

Return value: The first matching Element, or null if no match is found. If the selector string is invalid, the browser throws a SyntaxError DOMException.

3. Select an Element by ID

Use the hash symbol (#) followed by the element’s ID to select an element.

<h1 id="pageTitle">Welcome to JavaScript</h1>

<script>
const title = document.querySelector("#pageTitle");

console.log(title);
console.log(title.textContent);
</script>

The selector #pageTitle matches the element whose ID is pageTitle. Remember that CSS selector syntax requires the # symbol.

4. Select an Element by Class Name

Use a dot (.) followed by a class name to select the first element with that class.

<p class="message">First message</p>
<p class="message">Second message</p>

<script>
const message = document.querySelector(".message");

console.log(message.textContent); // First message
</script>

Even though both paragraphs have the message class, querySelector() returns only the first matching paragraph. To get every match, use querySelectorAll().

5. Select an Element by Tag Name

You can pass an HTML tag name without a prefix. The method returns the first matching element in document order.

<p>First paragraph</p>
<p>Second paragraph</p>

<script>
const paragraph = document.querySelector("p");

console.log(paragraph.textContent); // First paragraph
</script>

6. Select Elements Using Attribute Selectors

CSS attribute selectors let you find elements based on attributes and their values. For example, you can select an input by its type or an element by a custom data attribute.

<input type="email" name="email">
<button data-action="save">Save</button>

<script>
const emailInput = document.querySelector('input[type="email"]');
const saveButton = document.querySelector('[data-action="save"]');

console.log(emailInput);
console.log(saveButton);
</script>

7. Combine Multiple CSS Selectors

You can combine selectors to target elements more precisely. For example, a descendant selector finds an element inside another element, while a child selector matches only direct children.

<div class="card">
  <h2 class="card-title">JavaScript Tutorial</h2>
  <p>Learn DOM selection.</p>
</div>

<script>
const cardTitle = document.querySelector(".card .card-title");
const cardParagraph = document.querySelector(".card > p");

console.log(cardTitle.textContent);
console.log(cardParagraph.textContent);
</script>

The selector .card .card-title matches a descendant with the class card-title. The selector .card > p matches a paragraph that is a direct child of the card.

8. Select the First Element Matching Any of Several Selectors

Separate selector groups with commas when any one of them is acceptable. The method returns the first matching element in document order, not necessarily the element associated with the first selector in the string.

const element = document.querySelector(".notice, #warning, p");

console.log(element);

9. Change an Element’s Content and Style

After selecting an element, you can update its text, styles, classes, or attributes using standard DOM properties and methods.

<h2 class="heading">Old heading</h2>

<script>
const heading = document.querySelector(".heading");

if (heading !== null) {
  heading.textContent = "Updated heading";
  heading.style.color = "blue";
  heading.classList.add("active");
}
</script>

Using textContent is a good choice when inserting plain text. Avoid assigning untrusted content to innerHTML, because it can introduce cross-site scripting (XSS) vulnerabilities.

10. Search Within a Specific Parent Element

You do not have to search the entire document. Calling querySelector() on an element limits the search to its descendants.

<section id="profile">
  <h2 class="name">Alex</h2>
</section>

<section id="product">
  <h2 class="name">Laptop</h2>
</section>

<script>
const profile = document.querySelector("#profile");
const name = profile.querySelector(".name");

console.log(name.textContent); // Alex
</script>

Here, the second call searches only inside the profile section. It does not select the matching heading in the product section.

11. Handle Elements That Are Not Found

A selector may not match anything, especially when content is optional or the script runs before the relevant HTML has been parsed. Always consider the possibility of a null result before accessing element properties.

const button = document.querySelector("#submitButton");

if (button) {
  button.textContent = "Submit form";
} else {
  console.log("Submit button was not found.");
}

For scripts that run while the document is being parsed, place the script near the end of the body or wait for the DOMContentLoaded event.

document.addEventListener("DOMContentLoaded", () => {
  const heading = document.querySelector("h1");

  if (heading) {
    console.log(heading.textContent);
  }
});

12. querySelector() vs querySelectorAll()

Both methods accept CSS selectors, but they return different results.

Feature querySelector() querySelectorAll()
Return value First matching Element or null Static NodeList of all matches
Number of results At most one Zero or more
No match null Empty NodeList
Collection type Single Element NodeList
Updates after DOM changes A new call searches the current DOM Previously returned NodeList remains static

Use querySelector() when you need one matching element. Use querySelectorAll() when you need a collection of all matching elements.

13. Common Mistakes When Using querySelector()

  • Forgetting selector prefixes: Use #title for an ID and .title for a class.
  • Expecting all matches: querySelector() returns only the first match. Use querySelectorAll() for all matches.
  • Ignoring null: Check the result before accessing properties or methods.
  • Passing an invalid selector: Invalid CSS selector syntax throws a SyntaxError DOMException.
  • Using a selector before the element exists: Run the code after the relevant HTML has been parsed.
  • Confusing CSS escaping: Special characters in IDs or class names may need to be escaped with CSS.escape() when building a selector dynamically.

Categorized in:

Javascript, Js DOM,