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.
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
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
if (!myLinks.length) return;
That’s a tiny lesson.
This was originally posted on my own site.