Selecting DOM Elements in JavaScript with querySelector and querySelectorAll

We can use JavaScript with querySelector to select DOM element(s) as we do in CSS; this feature is an important one when we are working with HTML documents.

The cover image of the selecting DOM elements in JavaScript with querySelector and querySelectorAll. It is the logo of JavaScript language.

jQuery’s one of the best feature was that it made it possible to access the DOM easily. You could select anything with the same logic as you did in CSS, which was a significant update to the ID-based solution.

With the appearance of the Selectors API, our job is more straightforward – like with the classList – now when it comes to element manipulation.

The Selectors API and the New Functions

The querySelector and querySelectorAll were introduced in the Selectors API back in 2013.

Both of them are working on the document and on an element object too. You can also select elements inside a NodeList as you did with jQuery’s find method.

Today it is supported broadly almost get a 100% on Can I Use.

// querySelector() examples
var content = document.querySelector('.entry-content');
document.querySelector('a.is-highlighted:not([target="_blank"])');

// querySelectorAll() examples
document.querySelectorAll('button[type="submit"]');
content.querySelectorAll('p');

When you use the querySelector(All) methods, be aware of the followings:

  • If there is no result, you get back null.
  • The selector must be a valid CSS selector.
  • You can’t select pseudo-element.
  • You need an iteration technique if you use querySelectorAll(). There are more methods to iterate NodeLists in JavaScript. You can see them at the end of the article.

Select the First Element with querySelector() Method

This method gives back the first result of the given selector which could be anything – except pseudo-element – that works in CSS.

It has only one parameter, which is the selector. The selector can be anything which is a valid CSS selector. With modern selectors, we can almost select anything we want because we can use some of the pseudo-classes like :not() or :nth-child().

The return value is a NodeList with one element (if it exists). We can also add multiple selectors separated by a comma; although this is more useful in the case of querySelectorAll().

document.querySelector('a:not(.nav)');
document.body.querySelector('style[type='text/css'], style:not([type])');

Select the Elements with querySelectorAll() Method

The querySelectorAll() method is identical to the querySelector() but returns all the found value; this is also giving back a non-live NodeList.

var warnings = document.querySelectorAll('.alert.is-warning, .alert.is-error');

warnings.forEach((el) => {
    el.style.display = 'none';
});

Iterating Through NodeLists in JavaScript

While with the single version, we get back one value until then with the all method we get an object list. So it is essential to know what is a NodeList and how we can iterate through it using JS.

A NodeList is an object which contains a collection of nodes; these objects are array-like ones so we can iterate them with forEach().

Iterating with forEach Method

The reason for this whole section is the forEach() method which was broadly supported later for NodeLists than arrays. Today the support is well enough to use it, but we can get errors in some older browsers.

document.querySelector('.slide').forEach((el) => {
    el.style.display = 'none';
});

If you want broader browser support, you can use the call method to achieve it; note that this technique is not the best but can do the work.

var divs = document.querySelectorAll('div');

[].forEach.call(divs, (div) => {
    div.style.color = 'blue';
});

Iterating with a Simple For Loop

The most uncomplicated technique to iterate is a for-loop. Although it is easy, it isn’t so practical.

var divs = document.querySelectorAll('div');

for (var i = 0; i < divs.length; ++i) {
    divs[i].style.color = 'blue';
}
Need a web developer? Maybe we can help, get in touch!