In my last post, I wrote about the
Recently, my buddy Ryan Dejaegher was writing an
addClass() helper function. He wanted to be able to pass in either a reference to an element or a CSS selector string.
Ryan started with the CSS selector string functionality—and it worked perfectly, to his credit—but just for the purposes of this article, I’ll start the other way round.
The following is a simple helper function that accepts:
- A reference to an element
- The name of the class to be added
You would use it like so:
Refactoring our code
First, let’s refactor our function to make it a little more bulletproof:
The first thing you’ll notice is that we’ve changed the JSDoc comment block and renamed the
element parameter to the more generic
selector. This is to get ready for the next section, when the function will also accept a selector string instead of just a reference to an element.
Inside the function itself, we use the
instanceof operator to check if the
selector is an instance of the
Element base class. As explained in the MDN Web Docs,
Element is the most general base class from which all element objects (i.e. objects that represent elements) in a
We’re explicitly checking if the
selector is a reference to an element.
Supporting CSS selector strings
Now we’re going to add support for CSS selector strings. All we need to do is add a simple
else if clause like so:
else if condition, we use the
typeof operator to check if the
selector is a string. If so, we pass the
selector into the
querySelector() method. This lets us select the element first before we try to add the class.
With this in place, we now have the option to use our helper function by passing in a CSS selector string:
That’s it for this simple helper function! Feel free to use it in your projects. I’ve created a gist:
For more tiny helper functions, check out The Vanilla JS Toolkit.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!