The UpgradeJS Blog

Migrate jQuery to VanillaJS

When we join a project and it’s full of jQuery code everywhere that mostly handles simple functions like: selecting elements, add style to an element, handle AJAX request, and it was added a long time ago, maybe it’s time to start migrating small things to simple JavaScript code.

Reasons to migrate

Migrating jQuery code to VanillaJS can be someone’s task to reduce a big list of dependencies on a project which can be taking a considerable time to load on the browser, or maybe the plan is to improve performance on a page, or even handling dependencies at a library. Some jQuery code can also be found in a project because other JS code faced browser incompatibility.

Either way, jQuery may have helped previous developers, and at the time it may have seemed reasonable to use jQuery because it provided good development speed.

Using Webpack Bundle Analyzer opens a new window on one of our projects we can see that jQuery has the largest bundle size.

Graph showing bundle size of packages inside node modules folder

Loading all these jQuery internal dependencies to do a small change on your code can compromise the page’s loading time. Start by making small changes to the project to get a better loading time on it.

This blog post shows four of the more common jQuery functions you might use or find in your way which are easy to migrate.

Select elements

Selecting one or several elements from the DOM is a very common and one of the most used jQuery functions. In JavaScript we can do the same by calling querySelector() or querySelectorAll() in the context of the document.

// jQuery, select all instances of .element
$(".element");

// VanillaJS, select all instances of .element
document.querySelectorAll(".element");

// jQuery, select the FIRST instance of .element
$(".element:first");
  or
$(".element:").first();

// VanillaJS, select the FIRST instance of .element
document.querySelector(".element");

Events

A lot of event handling can be done using JavaScript and jQuery makes the syntax very easy to use .bind(),.on() or .click(). VanillaJS requires you to use addEventListener(), specify the event to listen to, and the callback function it should execute when this event happens.

// jQuery
$(".button").click((event) => {
  /* do something with click event */
});
$(".button").mouseenter((event) => {
  /* do something with mouse enter event */
});
$(document).keyup((event) => {
  /* do something with key up event */
});

// VanillaJS
document.querySelector(".button").addEventListener("click", (event) => {
  /* do something with click event */
});
document.querySelector(".button").addEventListener("mouseenter", (event) => {
  /* do something with mouse enter event */
});
document.addEventListener("keyup", (event) => {
  /* do something with key up event */
});

Some details to consider before making your transition:

  • if querySelector() doesn’t find the element on the page, it can fail if we call a function on it, while jQuery’s methods usually don’t;
  • With jQuery we can bind the event to all elements in a collection, in VanillaJS we have to loop through the elements (if we have many elements we want the event attached to and we need querySelectorAll);
  • jQuery supports multiple events in a single declaration when using on: $(…).on(“mouseenter mouseleave”, …) while vanilla js doesn’t, so we need multiple addEventListener calls;

AJAX

Use Fetch API opens a new window for fetching resources, this API provides a powerful way of dealing with requests and comes with good browser compatibility.

// jQuery
$.ajax({
    url: "https://www.example.com/"
  }).done((data) => {
    // do something with data
  }).fail((error) => {
    // do something with error
  });

// VanillaJS
fetch("https://www.example.com/")
  .then((data) => {
    // do something with data
  }).catch((error) => {
    // do something with error
  });

jQuery also provides $.get(URL, callback); and $.post(URL, data, callback); methods to request data from the server with an HTTP request, both receiving a URL as the first parameter. Following the HTTP pattern, $.get is used to retrieve data from the server and $.post is used to send data to the server, but it also can be used to get data from the server.

Styling

Instead of calling .css(), use .style in VanillaJS to change the style of selected elements.

// jQuery
$(".card").css("color", "#ABC123");

// VanillaJS
document.querySelector(".card").style.color = "#ABC123";

We can also use window.getComputedStyle(element) to get the values of all CSS properties of an element, we’re not covering it on this blog post but you can read more about it in the MDN docs. opens a new window

Conclusion

Migrating jQuery to VanillaJS can be easily handled, but on the other hand it can make your code bigger and require more checks to make your functions work properly, for example: searching for an element using document.querySelector and finding nothing will break if you call a function on it.

Some functions might not have full support across browsers and you would have to write more code to make this work.

Seems reasonable to keep jQuery in a project for specific reasons like browser support and to write less code on some functions. Keeping its usage to strictly in necessary functions, abstaining from using it in performance pages and in pages that deal with simple functionality is a good way to depend less on jQuery.

Final Tips

If you’re looking to change all your jQuery to vanilla JavaScript, check this list of common migration patterns. It is maintained by HubSpot on this website: You Might Not Need jQuery opens a new window .