A tiny lesson in query selection

We have a saying at Clearleft:

Everything is a tiny lesson.

I bet you learn something new every day, even if it’s something small. These small tips and techniques can easily get lost. They seem almost not worth sharing. But it’s the small stuff that takes the least effort to share, and often provides the most reward for someone else out there. Take for example, this great tip for getting assets out of Sketch that Cassie shared with me.

Cassie was working on a piece of JavaScript yesterday when we spotted a tiny lesson that tripped up both of us. The script was a fairly straightforward piece of DOM scripting. As a general rule, we do a sort of feature detection near the start of the script. Let’s say you’re using querySelector to get a reference to an element in the DOM:

var someElement = document.querySelector('.someClass');

Before going any further, check to make sure that the reference isn’t falsey (in other words, make sure that DOM node actually exists):

if (!someElement) return;

That will exit the script if there’s no element with a class of someClass on the page.

The situation that tripped us up was like this:

var myLinks = document.querySelectorAll('a.someClass');

if (!myLinks) return;

That should exit the script if there are no A elements with a class of someClass, right?

As it turns out, querySelectorAll is subtly different to querySelector. If you give querySelector a reference to non-existent element, it will return a value of null (I think). But querySelectorAll always returns an array (well, technically it’s a NodeList but same difference mostly). So if the selector you pass to querySelectorAll doesn’t match anything, it still returns an array, but the array is empty. That means instead of just testing for its existence, you need to test that it’s not empty by checking its length property:

if (!myLinks.length) return;

That’s a tiny lesson.

Have you published a response to this? :

Responses

1 Like

# Liked by dies das anernas on Thursday, February 21st, 2019 at 7:53pm

Previously on this day

3 years ago I wrote Variable fonts

The future of typography is here.

6 years ago I wrote Cake for America

Code for America. Cake for Anna.

12 years ago I wrote Culture

The world of Iain M Banks.

13 years ago I wrote The Future of Web Apps, day two

A running commentary of the fun at FOWA.

13 years ago I wrote The Future of Web Apps, day one

I’m back in London for a conference that means business.

17 years ago I wrote Wonderful Days

Earlier this week, I mentioned the trailers for the book Robota.

17 years ago I wrote Voice Box

In some ways, Voice Box is a pretty neat application. It downloads RSS feeds and turns them into sound files that you can save (and even sync to your iPod).

18 years ago I wrote Iran nets another revolt

Ben Hammersley’s article about the internet in Iran has been published in The Guardian. It’s a fascinating read.