Poor Mans jQuery
A lot of people use jQuery in their HTML/JavaScript applications. There’s nothing wrong with that. But I’ve seen a lot of people use jQuery only to make it easy to find elements and they are not using any of the other jQuery functions. It’s pretty clear that writing a single ‘ $ ‘ instead of the way longer usages of various function on the ‘document‘ object, like getElementById. One of the functions on the ‘document’ object is the querySelectorAll function. This function brings a similar experience to vanilla JavaScript by taking selectors as a parameter. So if we take a look at the example below. This show a fairly complicated selector you might find in an application.
I personally don’t like writing ‘document.querySelectorAll every time I need to find some things in the DOM, and many people with me. That’s why a lot of developers include jQuery in their project. To be able to use a similar syntax as jQuery is using I often add the following line somewhere at the start of my JavaScript code:
Here’s the earlier example, but with the poor-mans-jQuery added.
It’s not perfect and sometimes I add a context or something to that function if it is needed for that project, but it works fine in most cases.
As a last note, always look at the performance. If you are using selectors a lot, like in a big for-iteration, you might want to use the document.getElementsByClass function or something similar. These have less overhead and are somewhat faster.