Select Page

Category: loops

Do CSS Custom Properties Beat Sass Loops?

I reckon that a lot of our uses of Sass maps can be replaced with CSS Custom properties – but hear me out for a sec. When designing components we often need to use the same structure of a component but change its background or text color based on a theme. For example, in an alert, we might need a warning style, an error style, and a success style – each of which might be slightly different, like this: There’s a few ways we could tackle building this with CSS, and if you were asking me a couple of years...

Read More

A Bunch of Options for Looping Over querySelectorAll NodeLists

A common need when writing vanilla JavaScript is to find a selection of elements in the DOM and loop over them. For example, finding instances of a button and attaching a click handler to them. const buttons = document.querySelectorAll(".js-do-thing"); // There could be any number of these! // I need to loop over them and attach a click handler. There are SO MANY ways to go about it. Let’s go through them. forEach forEach is normally for arrays, and interestingly, what comes back from querySelectorAll is not an array but a NodeList. Fortunately, most modern browsers support using forEach on NodeLists anyway. buttons.forEach((button) => { button.addEventListener('click', () => { console.log("forEach worked"); }); }); If you’re worried that forEach might not work on your NodeList, you could spread it into an array first: [...buttons].forEach((button) => { button.addEventListener('click', () => { console.log("spread forEach worked"); }); }); But I’m not actually sure if that helps anything since it seems a bit unlikely there are browsers that support spreads but not forEach on NodeLists. Maybe it gets weird when transpiling gets involved, though I dunno. Either way, spreading is nice in case you want to use anything else array-specific, like .map(), .filter(), or .reduce(). A slightly older method is to jack into the array’s natural forEach with this little hack: [].forEach.call(buttons, (button) => { button.addEventListener('click', () => { console.log("array forEach worked"); }); });...

Read More
www.000webhost.com