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.
# Liked by dies das anernas on Thursday, February 21st, 2019 at 7:53pm