Skip to main content

How to Select an Element with querySelector in JavaScript

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

document.querySelector(selector) finds the first element on the page that matches a CSS selector, such as '.sale' or 'input[name=size]:checked', and returns it, so your code can read or change it. When nothing matches, it returns null.

Syntax​

Syntax
document.querySelector(<selector>)
<element>.querySelector(<selector>)
PartWhat it does
documentThe whole page. document.querySelector searches all of it.
<element>An element you already have. <element>.querySelector searches only inside it.
<selector>A CSS selector, as a string: 'li' for a tag, '.sale' for a class, '#total' for an id, or any combination CSS allows.

It returns the first matching element in the order the elements appear in the page, or null when no element matches. MDN's Document: querySelector() method page has the details.

The Example​

The example page has a shopping list of three items, two of them with the class sale. The script finds the first item on sale with querySelector('.sale') and shows its text below the list.

Step 1: Write the Code​

Create a file named index.html in a text editor, such as Visual Studio Code:

index.html, a page with a list of Apples, Bread and Cheese where Bread and Cheese have the class sale, a paragraph First item on sale with an empty strong element, and a script that puts the text of document.querySelector('.sale') into that strong element.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>querySelector</title>
</head>
<body>
<ul>
<li>Apples</li>
<li class="sale">Bread</li>
<li class="sale">Cheese</li>
</ul>
<p>First item on sale: <strong id="result"></strong></p>

<script>
const item = document.querySelector('.sale');
document.getElementById('result').textContent = item.textContent;
</script>
</body>
</html>

The dot in '.sale' means "the class sale", exactly as in a stylesheet. The last line puts the found item's text into the <strong> element, so you can see which item it is.

Step 2: Open It in a Browser​

Double-click index.html. It opens in your browser:

The page in Chromium: a bulleted list of Apples, Bread and Cheese, and below it First item on sale: Bread, with Bread in bold.

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.

What Happened​

  • querySelector('.sale') returned the Bread item. Two items have the class sale, and querySelector stops at the first one in the page.
  • item is the element itself, so item.textContent is its text, Bread.
  • Apples was skipped because it has no sale class.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the dot, querySelector('sale')It looks for a <sale> element and returns nullWrite the selector as in CSS: '.sale' for a class, '#result' for an id
Using the result without checking itWhen nothing matches, document.querySelector('.missing').textContent throws TypeError: Cannot read properties of null (reading 'textContent')Check for null before you use the result
Writing an invalid selector, such as 'li['SyntaxError: Failed to execute 'querySelector' on 'Document': 'li[' is not a valid selector.Fix the selector, and test it in a stylesheet if you're unsure
Expecting every matchYou get only the first oneUse querySelectorAll for all of them

Troubleshooting​

SymptomLikely causeFix
Cannot read properties of nullThe selector matched nothing, or the script ran before the element existedCheck the selector's spelling and case, and put the <script> after the elements it uses
The wrong element comes backAn element earlier in the page matches tooMake the selector more precise, for example 'ul .sale', or search inside one element
is not a valid selectorA typo in the selector, such as a missing ]Correct the selector

FAQ​

Can I search inside one element instead of the whole page?​

Yes. Call querySelector on that element: document.querySelector('ul').querySelector('li') returned the first item inside the list, Apples.

Can I use more complex selectors?​

Any CSS selector works. On this page, document.querySelector('li.sale:last-child') returned Cheese, and a selector such as 'input[name=size]:checked' finds the checked radio button of a group.

Should I use querySelector or getElementById?​

For an element with an id, both work: document.getElementById('result') and document.querySelector('#result') return the same element. querySelector is the one to use when the element has no id.

Conclusion​

document.querySelector takes the same selectors as CSS and gives you the first element that matches, or null. Check for null, and switch to querySelectorAll when you need every match.

Additional Resources​