DEV Community

Jack Cole
Jack Cole

Posted on

Learning querySelector in JavaScript

One tool that every web developer using JavaScript needs to master is the querySelector.

querySelector takes an argument of CSS-compatible selectors and returns the first element that matches them.

If your html document doesn't have a lot of content then your argument could be incredibly simple. For example, if we had the code below

<body>
  <div>
    Check out the fruit of my labors!
  </div>

  <div>
    <ul>
      <li>Apple</li>
      <li>Banana</li>
    </ul>
  </div>
</body>

We could return the list containing apple with document.querySelector('li'). Note that this will only select the first list item. To select them all we would instead use the .querySelectorAll function.

However, what if we had an enormous document. We would need to be much more specific in how we select certain bits of information. For example, we could pass the following string

document.querySelector('div.fruits ul li p ul li ')

This would search our document for a div with a className of fruits. It would then look for the first unordered list that is a child of the div. Then it would find a list in the unordered list, then a paragraph in that list, then an unordered list in the paragraph, and finally a list inside of the unordered list.

As we continue to grow as developers it is crucial to have a solid understanding of the basics of selecting portions of your documents. Once mastered, querySelector will allow you to create interaction on any specific section of you webpages and applications!

Latest comments (0)