JavaScript allows commands for complicated query searches. This article will show you how to use querySelector() and querySelectorAll() methods in the interface to find elements contained in the CSS selectors.

However, these two methods show different outputs when they fail to find a particular element. Let's find out more about these methods, their syntaxes, and examples.

Syntax and general outlook

When it comes to querySelector(), this method allows users to discover an element that matches one or more CSS selectors. Please note that you're free to utilize this method in any document or HTML element. Syntax-wise, this method is expressed in a statement form:

const element = parentNode.querySelector(selector);

Please mind that when working with the document, the syntax is then changed to match such a method and looks like this:

const element = document.querySelector(selector);

In the first example, though, a selector is a CSS selector or such a group that matches the descendant elements of the parentNode. If you try using such a command when no element in scope matches one or more CSS selectors, your return will be null.

As for the querySelectorAll() method, it finds all appropriate elements matching one or more CSS selectors. Syntax should be like this:

const elementList = parentNode.querySelectorAll(selector);

Remember that it returns elements in the form of a static NodeList. If no such elements are found, this static NodeList would be empty.

Because of different returns, these statements, although similar, behave differently in situations where no elements are found. It is a minor issue, but you should definitely keep it in mind.

Direct descendants and :scope pseudo-classes

Because querySelector() requires the full document with code, it would be troublesome to explain it with complex examples. Instead, let us show you how this statement behaves when working with a :scope pseudo-class:

const parentElement = document.querySelector('#parent');
let allChildren = parentElement.querySelectorAll(":scope > span");
allChildren.forEach(item => item.classList.add("blue"));

In this example, when inserted into a web page, the use of a :scope allows retrieving exactly what we need. In particular, you can get the direct children of the parentElement. When formatted with proper HTML and CSS, this code passes the attributes by finding the appropriate CSS selectors and marking them in an appropriate color.

Document.querySelectorAll() Method

Even though we mentioned the NodeList already, showing how this method works would be representative. Imagine that you need to obtain a NodeList of all the <h1> elements in your document or the HTML element. For that purpose, you can use the following code statement:

const matches = document.querySelectorAll("h1");

Once the NodeList with the H1 element is returned, you are welcome to examine it just like any other array. However, if it's empty, no matches would be displayed in the NodeList. For filtering and searching purposes, feel free to use any JavaScript looping techniques to skim through the object properties you need.

Document.querySelector() Method

Is it different when you need to match a single element to the CSS selector? With this method, use the following syntax:

document.querySelector('.className h1'); // Search by class + tag
document.querySelector('#id'); // Search by id (is unique)

In this case, we don't just want to select all H1s from the document. In turn, we specify that we need to select H1s from a particular class or id by indicating the necessary properties.

Because the output is not displayed in the format of NodeList, you can freely browse through the return. However, don't forget that null is the output you get if no matches are found.

Nuanced HTML examples

What if we try to show you even more examples, but now, embedding more HTML cases with CSS elements? In a text document, insert the following HTML code:

<body>
  <div class='description'>
    <p>
      Sample Text
    </p>
  </div>
  <button onclick='changeColor()'>Change</button>
</body>

In this instance, we introduce Sample Text and a button, which, on click, changes a color. All seems nice and logical, especially when you try utilizing the querySelector() to find an appropriate element. The request will look like this:

function changeColor () {
    var element = document.querySelector('.description p')
    element.style.border = '1px solid green'
}

Not only does this code indicate the function changeColor, which is located in the HTML code before, it also includes more query specifications. This request also capitalizes on finding elements with a description class.

In this class, a <p> tag has to be found. Also, the border-style property has been included in the end to specify the query. This way, the querySelector() method allows forming structured queries, which can even be found in each one's structure.

Wrapping up

Because the functionality of querySelector() and querySelectorAll() methods is huge, don't forget that these two have various behaviors regarding returns. While the querySelector() returns null if no appropriate elements have been found, querySelectorAll() still returns a NodeList. Because of a different behavior between the two, carefully think about utilizing one method over another.

Because the querySelector() method requires HTML and CSS to operate, we recommend testing it in your pet projects. In particular, try finding a container, HTML tag, or a .outer.

Also, because this method can work with the Document and Element, learn more about the two not to mess up with one another. Also, our example on the use of a :scope pseudo-class represents how to retrieve direct children of the ParentElement using the querySelector().

Last but not least, don't forget that JavaScript presents various options to meet the exact particular needs. You can experiment with poly-filling of document.querySelectorAll() using the manual traversing, CSS behaviors, and web components.