jQuery has become ubiquitous on the web and in WordPress. Many of its components are in the WordPress core software, the admin uses it heavily, and it’s readily available for front-end use as well. We enqueue it without thought when we need it, but should we always do so?
I tend to think not, and in this article, I’ll show you why, and how you can achieve the same results without jQuery.
Why jQuery Is Great
Complex DOM traversals and animations become a single line of strung together functions – easy-peasy.
Why jQuery Is Not Great
Expanded jQuery clocks in around 250kb and compressed it’s about 85kb. The version of jQuery core WordPress uses is only about 30kb, but that’s still way too much if you just need to select a couple of links and change their colors.
To put all that into perspective, if your site has 1 million unique views a month you’ll generate 30GB of traffic from unused code – what a waste!
jQuery('#my-link') you could have just written
document.getElementById('my-link'). Yes, it’s a bit longer, but not 30kb longer!
#1. Select Elements
Selecting elements is almost as easy in vanilla JS as it is in jQuery.
Where vanilla JS starts to fall short is complex selections like
#2. Traverse The DOM
You’d expect to be able to select the first list item, it’s next sibling would be the next list item. In jQuery this is how it works but under the hood text nodes need to be factored in as well. The next sibling of the first list item is actually a text node with the text “List Item One.” The next sibling of that node is the second list item.
The two conclusions: text nodes need to be considered when traversing the DOM and text can only be parsed out of text nodes, not their containing elements as you may be used to in jQuery. Here’s how we could traverse the HTML above:
#3. Set and Get Attributes
#4. Looping Through Nodes
While some lines can be a bit more lengthy than the jQuery counterparts, you’ll still use a lot less code to get things done. You’ll save bandwidth, write leaner code and learn some valuable pure JS in the process.