DEV Community

Ian Jones
Ian Jones

Posted on • Edited on

6 3

Select an Element with document.querySelector

If you would prefer to watch this post, you can do so with this community resource lesson on egghead.io.

You may not always want to select the first child of an element. document.querySelector will match elements based on a pattern you give it. Say we have a page that looks like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Select an Element with document.querySelector</title>
  </head>
  <body>
    <ul>
      <li>Peanut Butter Falcon</li>
      <li>Knives Out</li>
    </ul>
  </body>
</html>

Instead of accessing the first li element with firstElementChild you can use document.querySelector('li').

If you guessed <li>Peanut Butter Falcon</li> you were right. Don't feel bad if you got it wrong though, you weren't supposed to know the answer!

How do we get the element with the inner text of 'Knives out' with document.querySelector though?

Right now we can't. We need to assign id's to the elements like this:

<ul>
  <li id="movie-1">Peanut Butter Falcon</li>
  <li id="movie-2">Knives Out</li>
</ul>

Now we can call document.querySelector('#movie-2') to get our <li id="movie-2">Knives Out</li> element. The # is how we tell querySelector we are looking for an id on an element.

Note that this id should be unique in this DOM tree. You never want to give two elements the same id. This will cause some frustrating bugs!

What are some ways you've used querySelector?

tutorial image

Next.js Tutorial 2025 - Build a Full Stack Social App

In this 4-hour hands-on tutorial, Codesistency walks you through the process of building a social platform from scratch with Next.js (App Router), React, Prisma ORM, Clerk for authentication, Neon for PostgreSQL hosting, Tailwind CSS, Shadcn UI, and UploadThing for image uploads.

Watch the video →

Top comments (4)

Collapse
 
tobymosque profile image
Tobias Mesquita • Edited

Would be better to say querySeletor expect a css selector, so li + li or ul:nth-child(2) or li:nth-of-type(2) would work.

Collapse
 
theianjones profile image
Ian Jones

Thanks for the feedback! I appreciate it.

Collapse
 
willjohnsonio profile image
Will Johnson

Loving this series about the DOM keep it up!

Collapse
 
theianjones profile image
Ian Jones

Thanks Will!

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!