How to replace jQuery with Vanilla JavaScript

Sharing is Caring

I’ve always believed that JavaScript probably wouldn’t have achieved so much with the web without the jQuery library having existed. jQuery is a really popular JavaScript library that helps really simplify manipulating HTML with JavaScript whether it be CSS, animations or even doing Ajax.

Why jQuery
A large part of the reason we needed jQuery was because of a lack of browsers adopting the standards in a timely manner. Internet Explorer was not regularly being updated for a large amount of time even though it had the a very large percentage of the market.

Firefox, Chrome and even Safari were releasing more frequently which was causing a huge disparity. Developers were using Firefox, Chrome, and Safari which means that support for Internet Explorer was really low.

Why Use Vanilla Javascript?
Over the last, three or so years jQuery has become less useful as a library because most of the browsers are now really starting to follow standards. JavaScript has really matured as a language and really evolved with newer APIs. Probably the best example of this is that the Selectors API has made it so much easier to select elements of the DOM.

Should you learn jQuery?

I believe you will benefit a lot more by learning vanilla JavaScript than spending time trying to learn jQuery. Frameworks will come and go but the fundamentals of languages generally don’t change.

There’s some really clever programming techniques that are used in jQuery that can make you a better programmer. You can pickup a lot of this from actually reading through the library and tinkering with it though.

Should you use jQuery in 2018 and 2019?

As a programmer, and technology manager I think it’s really important to use the right tools and technologies. I don’t think there’s always a clear cut answer to whether you should use a tool or not. There are times where I think jQuery is still really valuable but there are a lot of times where I don’t think it is valuable.

Single Page Apps
If you are working with modern JavaScript libraries or single page apps(spa) I don’t think you should really use jQuery. If you are using Vue or React you definitely shouldn’t use it because of the virtual dom.

WordPress Sites
For a really simple WordPress site or a web site built with another content management system it probably makes sense to use jQuery.

Third Party Libraries
I believe that if you are developing a library that will be used externally you should avoid adding jQuery as a dependency. Often a few lines of utility code will allow us to avoid adding another dependency. And if you’re only targeting modern browsers, you can probably avoid jQuery altogether.

Make sure that you understand the benefits before you just ditch jQuery. Often it’s doing a lot more than is being realized which means that simply removing it means you could be taking on a lot of extra work.

If it’s simply an issue of the size of the file, it’s been possible to do custom builds of jQuery for a long time. To do custom builds you can do that from their github page.

How to replace jQuery with Vanilla JavaScript

I generally have used jQuery for five different things: selecting elements (jQuery() or $()), events, css, document ready or ajax calls.

Replacing jQuery is really easy now that Internet Explorer is basically dead, and that Edge is now using the Chrome engine.

Selecting Elements

Selecting elements of the DOM in vanilla javascript is relatively easy now that all of the browsers are more standardized. Typically you can use document.getElementById() or document.querySelector() or document.querySelectorAll()


// To select all of the copies of a div called "inner-element" I would do something like
jQuery('.inner-element').

// To select one element I could do 
document.querySelector('.inner-element')

// In vanilla JavaScript, I can do this like so
document.querySelectorAll('.inner-element')

querySelectorAll returns a NodeList that contains all elements that would match or selector. To iterate over the elements we can use a forEach.

Events

Adding events in vanilla javascript is pretty easy especially with the ES6 support we now enjoy in pretty much all browsers. I use the addEventListener and pass in the event type, and then a function that accepts an element.

Creating or Triggering Events can be done by using the dispatchEvent function

Add a click event to a button using a regular old event function.

document.querySelector('button').addEventListener('click', function (e) { doSomething(); }) 

I usually use fat arrow functions instead of regular functions now, so it would look more like

this:document.querySelector('button').addEventListener('click', (e) => { doSomething(); });

Styling Elements or .css()

For the most part, styling events in vanilla JavaScript can be done by assigning values to the equivalent name in .style. For example, colouring the text so it’s green could be done like this

document.getElementById("coloredBy").style.color = colorCode; // green or #008000 

Hiding and Showing Elements

In the past, one of the common things I did with jQuery was to show or hide elements dynamically. Hiding and showing is basically a helper function that sets the style.display element to “none” or “block” depending on the desired state.

Adding and Removing CSS Classes

Using the classList property we can add, remove, and toggle classes pretty easily. It works the exact same as jQuery addClass, removeClass, and toggleClass methods.

Document Ready

Waiting for the DOM to be fully loaded can be pretty tricky because window.onload isn’t exactly equivalent. window.onload will fire when all images, scripts, and links have loaded so it can also be quite useful. DOMContentLoaded doesn’t wait for images and what not to finish downloading.

DOMContentLoaded is supported by over 90%+ of browsers, basically everything under Internet Explorer 9 is broken. Thankfully, there’s almost no chance of anybody using IE9 or below at this time.

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

Network Requests Without jQuery

Now that ES6 support is excellent in basically all browsers, it’s possible to use the fetch method which returns a promise. fetch() takes a url as an argument and then returns the promise. You can use and handle the promise the same way you normally would.

fetch('http://example.com/somefile.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });

Fetch also can taken an optional second parameter for setting up the request. For example, the init object could include attributes like method, cache, credentials, headers, redirect, body, etc.

Summary

Hopefully, this is a good helpful start for moving away from jQuery and why you should consider it.

In the early 2000 – 2010s, jQuery was an amazing library that really helped move web development forward. It really helped draw people’s attention to JavaScript and showed off how powerful it could be for building great user experiences.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.