DEV Community

Ian Jones
Ian Jones

Posted on • Updated on

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?

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!