DEV Community

Jack Cole
Jack Cole

Posted on

2 1

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!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay