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

Related posts

JavaScript

Inside me there are two wolves. They’re both JavaScript.

Bugblogging

Also, tipblogging.

Suspicion

Responses to my thoughts on why developers would trust third-party code more than a native browser feature.

Trust

I’m trying to understand why developers would trust third-party code more than a native browser feature.

When should there be a declarative version of a JavaScript API?

If the JavaScript API requires a user gesture, maybe it’s time for a new button type.

Related links

“Just” One Line - Jim Nielsen’s Blog

There’s a big difference between the interface to a thing being one line of code, and the cost of a thing being one line of code.

A more acute rendering of this sales pitch is probaly: “It’s just one line of code to add many more lines of code.”

And as Chris puts it:

Every dependency is a potential vulnerability

Tagged with

The quiet, pervasive devaluation of frontend - Josh Collinsworth blog

It’s like CSS exists in some bizarre quantum state; somehow both too complex to use, yet too simple to take seriously, all at once.

In many ways, CSS has greater impact than any other language on a user’s experience, which often directly influences success. Why, then, is its role so belittled?

Writing CSS seems to be regarded much like taking notes in a meeting, complete with the implicit sexism and devaluation of the note taker’s importance in the room.

Tagged with

Why I don’t miss React: a story about using the platform - Jack Franklin

This is a great case study of switching from a framework mindset to native browser technologies.

Though this is quite specific to Jack’s own situation, I do feel like there’s something in the air here. The native browser features are now powerful and stable enough to make the framework approach feel outdated.

And if you do want to use third-party dependencies, Jack makes a great case for choosing smaller single-responsibility helpers rather than monolithic frameworks.

Replacing lit-html would be an undertaking but much less so than replacing React: it’s used in our codebase purely for having our components (re)-render HTML. Replacing lit-html would still mean that we can keep our business logic, ultimately maintaining the value they provide to end-users. Lit-Html is one small Lego brick in our system, React (or Angular, or similar) is the entire box.

Tagged with

Trust • Robin Rendle

Robin adds a long-zoom perspective on my recent post:

I am extremely confident that pretty much any HTML I write today will render the same way in 50 years’ time. How confident am I that my CSS will work correctly? Mmmm…70%. Hand-written JavaScript? Way less, maybe 50%. A third-party service I install on a website or link to? 0% confident. Heck, I’m doubtful that any third-party service will survive until next year, let alone 50 years from now.

Tagged with

Trust and suspicion | Keenan Payne

Another thoughtful reponse to my recent post.

Reflections on native browser features and third-party library adoption.

Tagged with

Previously on this day

8 years ago I wrote Variable fonts

The future of typography is here.

11 years ago I wrote Cake for America

Code for America. Cake for Anna.

17 years ago I wrote Culture

The world of Iain M Banks.

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

A running commentary of the fun at FOWA.

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

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

22 years ago I wrote Wonderful Days

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

22 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).

23 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.