DEV Community

Cover image for Why jQuery 4 is a good reminder to stop using jQuery
Megan Lee for LogRocket

Posted on • Originally published at blog.logrocket.com

Why jQuery 4 is a good reminder to stop using jQuery

Written by Shalitha Suranga✏️

jQuery has a long and respected history, yet, its new release of jQuery v4 beta is out with no interesting features for modern web developers. There are several reasons why it’s a good time to stop using jQuery:

  1. Modern browsers and native JavaScript APIs now natively support all features that jQuery provides, making it redundant and its utility functions obsolete
  2. Using jQuery unnecessarily increases web app bundle size and reduces performance compared to native implementations
  3. The release of jQuery 4 confirms its obsolescence by lacking significant new features, focusing on survival, and highlighting that native JavaScript and modern frameworks have surpassed it.
  4. jQuery’s migration to ES modules and adoption of modern practices in jQuery 4 adds nothing new for web developers
  5. Using jQuery with modern frontend frameworks like React, Vue, and Angular can conflict with their architectures and coding recommendations
  6. Modern frontend frameworks emit production code with polyfills, so developers don’t need to use the jQuery API to create web pages for older browsers

We’ll explore these points in more detail and dive into why jQuery v4 concludes a decade-long journey by comparing its available features with native JavaScript web APIs.

The golden era of jQuery before v4

From the inception of frontend web development, developers used JavaScript to implement user-friendly web frontends by updating HTML elements dynamically.

In the early 2000s, there were no fully-featured, component-based, modern frontend development libraries like React, and browsers also didn’t offer advanced CSS features like animations and high-level, developer-friendly, fully-featured DOM manipulation API, so developers had to write many code lines with the existing web APIs to build web frontends — they even had to write code to solve browser compatibility issues with AJAX communication APIs.

jQuery solved these issues by offering shorthand functions for DOM manipulation and a cross-browser AJAX API, so every web developer included the jQuery script in their web apps.

As everyone recommends a component-based frontend framework today, jQuery was the most recommended approach for creating dynamic web frontends in the mid-2000s when the usage of jQuery reached the peak before its downfall:
Demonstration From Inspect Element Showing That The Official Bootstrap 3.4 Website Uses jQuery
The official Bootstrap 3.4 website uses jQuery from the official CDN

In the mid 2000s, jQuery v1 to v3 was used in:

  • Every popular website HTML template to implement sliders, image galleries, etc.
  • Web apps to do DOM manipulation and make HTTP/AJAX calls with Internet Explorer support
  • Bootstrap to implement components like modals, dropdowns, etc.
  • Every dynamic WordPress template and plugin for DOM manipulation

The state of jQuery with the release of v4

jQuery released the first beta release in February 2024 and the second in July  —  codebase maintainers are planning to make a release candidate version soon. The v4 release of jQuery has the following major changes:

  • Dropped the support for IE 10 and older web browser versions
  • Removed methods that have been already deprecated, such as jQuery.isArray()
  • Supports using the HTML content created with Trusted Types API
  • Supports using native JavaScript binary data in AJAX methods
  • The jQuery codebase was migrated into ES modules from AMD (requirejs modules) with the Rollup bundler

With the release of jQuery v4 beta, it tries to modernize its codebase by using ES modules and reduce the bundle size by dropping IE 10 support. You can read more about the upcoming jQuery v4 release from this official blog post.

Why jQuery v4 confirms its downfall

The release of jQuery v4 beta is not indeed a cause to stop looking at jQuery, but the growth and the future shown through the v4 release confirms jQuery’s downfall in modern web technology. This slowly started when the browser standard started offering developer-productivity-focused high-level DOM manipulation features and advanced features in CSS that helped developers implement dynamic styles without using JavaScript.

jQuery v1 to v3 undoubtedly implemented cross-browser developer-friendly features that browsers didn’t natively offer. For example, jQuery’s Sizzle selector engine helped developers query DOM elements before browsers implemented document.querySelectorAll(). Moreover, $.ajax() was the previous developers’ fetch() due to browser compatibility issues of the inbuilt AJAX API.

Scrolling Through An Old StackOverflow Answer Recommends Using jQuery Over Old Native Web APIs
An old StackOverflow answer that recommends using jQuery instead of old native web APIs

During the jQuery v2 to v3 period, HTML, JavaScript, CSS, and web APIs were drastically enhanced and offered standard APIs for jQuery features thereby making jQuery an obsolete choice.

jQuery tried to survive by adhering to standard APIs, such as supporting the standard Promise interface in v3, and removing duplicate code, but standard browser features won the modern developer’s heart. jQuery released v4 not with features but with enhancements to remain relevant in modern web technology.

jQuery v4 brings you a 27kb gzipped bundle increment for the features that your web browser natively ships with 0kb client-side JavaScript code!

jQuery vs. native browser APIs

Let’s compare jQuery vs. native browser API code for several development requirements side-by-side and see how modern web APIs make jQuery obsolete.

Create a new HTML file and link the jQuery v4 beta version via the official CDN as follows to get started:

<script src="https://code.jquery.com/jquery-4.0.0-beta.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Selecting DOM elements

Modern frontend libraries and frameworks offer the ref concept for accessing DOM element references, but web developers often have to query DOM elements if they don’t depend on a specific frontend framework. See how document.querySelectorAll() implements easy, native DOM selection similar to jQuery:

<ul class="items">
 <li><label><input type="checkbox" checked>JavaScript</label></li><div>
 <li><label><input type="checkbox">Python</label></li><div>
 <li><label><input type="checkbox" checked>Go</label></li><div>
</ul>
Enter fullscreen mode Exit fullscreen mode
// jQuery:
const elms = $('.items input[type=checkbox]:checked');
console.log(elms.toArray());

// Native:
const elms = document.querySelectorAll('.items input[type=checkbox]:checked');
console.log(elms);
Enter fullscreen mode Exit fullscreen mode

Result:

DOM Elements Being Selected Using jQuery
Selecting DOM elements with CSS queries using jQuery and native web APIs

jQuery offers the closest() method to traverse back and find a matching DOM node for a given selector. The native DOM API also implements the same method using the OOP pattern:

// jQuery:
const elms = $('.items input[type=checkbox]:checked')
             .closest('li');
console.log(elms.toArray());

// Native:
const elms = document.querySelectorAll('.items input[type=checkbox]:checked');
console.log([...elms].map(e => e.closest('li')));
Enter fullscreen mode Exit fullscreen mode

Result:
Selecting Closest DOM Elements Using jQuery And Native Web APIs
Selecting the closest DOM elements using jQuery and native web APIs

Some jQuery features don’t have identical, shorthand alternatives in modern standard DOM API, but we can use existing DOM API methods effectively with modern JavaScript features.

For example, jQuery supports the non-standard :contains(text) selector, so we have to implement it with the filter() array method as follows:

// jQuery:
const elms = $('.items li label:contains("Java")');
console.log(elms.toArray());

// Native:
const elms = document.querySelectorAll('.items li label');
console.log([...elms].filter(e => e.textContent.includes('Java')));
Enter fullscreen mode Exit fullscreen mode

Result:
Filtering Elements Containing A Specific Text Segment Using jQuery Alongside Native Web APIs
Filtering elements that contain a specific text segment using jQuery and native web APIs

The querySelectorAll() method takes the power of modern CSS pseudo-classes to offer a better native alternative for the jQuery find() function. For example, we can use the :scope pseudo-class to scope native query selector calls similar to the jQuery find() function:

<div class="pages">
  <div class="page-1">
    <h2>Web</h2>
    <div class="pages">
      <div class="page-1">
        <h3>TypeScript</h3>
      </div>
    </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
// jQuery:
const elms = $('.pages')
             .find('.pages > .page-1');
console.log(elms.toArray());

// Native:
const elms = document.querySelector('.pages')
             .querySelectorAll(':scope .pages > .page-1');
console.log(elms);
Enter fullscreen mode Exit fullscreen mode

Result:
Scoping DOM Element Selectors Using jQuery And Native Web APIs
Scoping DOM element selectors using jQuery and native web APIs

Retrieving and updating DOM attributes

The class attribute, element-specific attributes, and custom data attributes are common HTML attributes that web developers often have to retrieve and update while developing web apps.

In the past, developers had to manipulate the native className property manually to update element class names, so they used jQuery’s addClass(), removeClass(), and toggleClass() pre-developed function implementations. But now, the native classList object implements better class attribute value handling support:

<div id="item-1" class="item item-lg item-vl">#item-1</div>
<div id="item-2" class="item item-lg item-vl">#item-2</div>
Enter fullscreen mode Exit fullscreen mode
// jQuery:
const elm = $('#item-1');
elm.addClass('item-sel')
  .removeClass('item-vl')
  .toggleClass('item-lg')
  .toggleClass('item-lg');
console.log(elm.attr('class'));

// Native:
const elm = document.querySelector('#item-2');
const cl = elm.classList;
cl.add('item-sel');
cl.remove('item-vl');
cl.toggle('item-lg');
cl.toggle('item-lg');
console.log(elm.className);
Enter fullscreen mode Exit fullscreen mode

Result:
Updating The Class Attribute Values Using jQuery And Native Web APIs
Updating the class attribute values using jQuery and native web APIs

Meanwhile, the getAttribute() and setAttribute() native DOM methods become a standard replacement for the well-known jQuery attr() shorthand function:

// jQuery:
const elm = $('#item-1');
elm.attr('title', 'Element #1');
console.log(elm.attr('title'));

// Native:
const elm = document.querySelector('#item-2');
elm.setAttribute('title', 'Element #2');
console.log(elm.getAttribute('title'));
Enter fullscreen mode Exit fullscreen mode

Result:
Changing And Retrieving HTML Element Attributes Using jQuery And Native Web APIs
Changing and retrieving HTML element attributes using jQuery and native web APIs

jQuery recommends developers use its attr() function to set custom data attributes, but now you can use the inbuilt dataset property for more productive data attribute retrieval/modification as follows:

// jQuery:
const elm = $('#item-1');
elm.attr('data-player-name', 'John')
elm.attr('data-score', '200');
console.log(`${elm.attr('data-player-name')}: ${elm.attr('data-score')}`);

// Native:
const elm2 = document.querySelector('#item-2');
elm2.dataset.playerName = 'John';
elm2.dataset.score = '200';
console.log(`${elm2.dataset.playerName}: ${elm2.dataset.score}`);
Enter fullscreen mode Exit fullscreen mode

Result:
Updating Custom Data Attributes Using jQuery And Native Web APIs
Updating custom data attributes using jQuery and native web APIs

DOM element manipulation

In the past, most developers used jQuery for DOM manipulation since the native DOM manipulation API didn’t offer developer-productivity-focused features. Now every modern standard web browser implements productive, high-level, inbuilt DOM manipulation support.

Creating and appending elements are the most frequent operations in DOM manipulation tasks. Here is how it’s done using both jQuery and native web APIs:

<ul id="list-1">
 <li>JavaScript</li>
</ul>
<ul id="list-2">
 <li>JavaScript</li>
</ul>

// jQuery:
$('#list-1').append($('<li>TypeScript</li>'));

console.log($('#list-1').html());

// Native:
const ts = document.createElement('li');
ts.textContent = 'TypeScript';
document.querySelector('#list-2').append(ts);

console.log(document.querySelector('#list-2').innerHTML);
Enter fullscreen mode Exit fullscreen mode

Result:
Creating And Appending New HTML Elements With jQuery And Native Web APIs (Wrapped With setTimeout For Better Demonstration)
Creating and appending new HTML elements with jQuery and native web APIs (wrapped with setTimeout for better demonstration)

jQuery also implemented prepend(), before(), and after() shorthand functions for productive DOM manipulation  —  now the native DOM API implements all these methods as well.

Look at the following example that demonstrates before() and after():

<div id="item-1">#item-1</div></br>
<div id="item-2">#item-2</div>
Enter fullscreen mode Exit fullscreen mode
// jQuery
const createElm = () => $('<h3>list-1</h3>');

const elm = $('#item-1');
elm.before(createElm());
elm.after(createElm());

// Native:
const createElm = () =>  {
 const e = document.createElement('h3');
 e.textContent = 'item-2';
 return e;
}

const elm = document.querySelector('#item-2');
elm.before(createElm());

`elm.after(createElm())`;
Enter fullscreen mode Exit fullscreen mode

Result:
Using Before() And After() Functions Using jQuery And Native Web APIs
Using before() and after() functions using jQuery and native web APIs

Animating DOM elements

If you are an experienced web developer who built web apps more than a decade ago, you know how jQuery fadeIn(), fadeOut(), and animate() functions helped you to make your web apps more interactive. These animation functions even supported animation easing to build smoother animations.

Native CSS animations/transitions and JavaScript web animation API made jQuery animation API obsolete. Here is how you can implement fadeIn() with the standard web animations API:

<div id="item-1" style="display: none">#item-1</div>

<script>
// jQuery:
$('#item-1').fadeIn(1000);
</script>
Enter fullscreen mode Exit fullscreen mode
<div id="item-2" style="opacity: 0">#item-2</div>

<script>
// Native:
document.querySelector('#item-2')
       .animate([{ opacity: 1}], { duration: 1000, fill: 'forwards'});
</script>
Enter fullscreen mode Exit fullscreen mode

Result:
Fade-in Animations Using jQuery And Native Web Animations API. #Item-1 And #Item-2 Fade In
Fade-in animations using jQuery and native web animations API

You can use the native animate() method as a standard alternative for the old-fashioned, non-standard jQuery animate() function to create high-performance, smooth animations using pure JavaScript without switching CSS class names:

<div id="item-1">#item-1</div>

<script>
// jQuery
$('#item-1').animate({
 fontSize: '26px',
 duration: 1000
});
</script>

<div id="item-2">#item-2</div>

<script>
// Native
document.querySelector('#item-2')
       .animate([{ fontSize: '26px'}], { duration: 1000, fill: 'forwards'});
</script>
Enter fullscreen mode Exit fullscreen mode

Result:

Example Of Creating Animations With jQuery And Native Web Animations API. #Item-1 And #Item-2's Font Sizes Become Larger
Creating animations with jQuery and native web animations API

jQuery dynamically updates CSS properties to construct animation keyframes, but the standard animations API natively renders animations, so the native web animation-based approach is indeed performance-friendly.

Moreover, you can create CSS-only animation loops without even using JavaScript, as explained in this comprehensive tutorial.

Working with browser events

Every browser typically lets developers attach event handlers through JavaScript for various standard events. Every web app uses DOM events to make the web interface interactive for users. jQuery offers shorthand on() and off() functions to register event handlers, but the native DOM API also offers self-explanatory functions for the same purpose:

<button id="btn1">0</button>
<button id="btn2">0</button>
Enter fullscreen mode Exit fullscreen mode
// jQuery:
function handleClick(e) {
 const btn = $(e.target);
 const val = parseInt(btn.text()) + 1;
 btn.text(val);
 if(val === 5)
   btn.off('click', handleClick);
}

$('#btn1').on('click', handleClick);

// Native:
function handleClick(e) {
 const btn = e.target;
 const val = parseInt(btn.textContent) + 1;
 btn.textContent = val;
 if(val === 5)
   btn.removeEventListener('click', handleClick);
}

document.querySelector('#btn2')
       .addEventListener('click', handleClick);
Enter fullscreen mode Exit fullscreen mode

Result:
Attaching And Removing Event Handlers With jQuery And Native Web APIs
Attaching and removing event handlers with jQuery and native web APIs

Both jQuery and the native DOM API offer shorthand ways to attach event listeners:

// jQuery:
$('#btn1').click(() => {});

// Native:
document.querySelector('#btn2').onclick = () => {};
Enter fullscreen mode Exit fullscreen mode

jQuery also offers the one() function to trigger an event handler once — now every standard web browser supports the once option for the same purpose:

// jQuery
$('#btn1').one('click', () => {});

// Native:
document.querySelector('#btn2').addEventListener('click', () => {}, {
 once: true
});
Enter fullscreen mode Exit fullscreen mode

Communicating with web services

Past monolithic web apps frequently sent HTTP requests to the backend server to get new pages with updated data  —  web apps rendered the entire page for each major user action.

Later, developers made better, interactive web apps by updating a part of the webpage by requesting HTML content via AJAX. They used jQuery to send AJAX requests because of browser compatibility and productivity issues with the built-in AJAX API.

Now developers can use the standard fetch() function instead of jQuery’s AJAX features:

// jQuery:
$.ajax({
 url: 'https://corsproxy.io/?https://example.com'
})
.then(data => {
 console.log(data.length);
});

// jQuery:
$.get('https://corsproxy.io/?https://example.com')
.then(data => {
 console.log(data.length);
});

// Native:
fetch('https://corsproxy.io/?https://example.com')
 .then(req => req.text())
 .then(data => {
   console.log(data.length);
 });
Enter fullscreen mode Exit fullscreen mode

Result:
Sending HTTP Requests With jQuery And Native Web APIs
Sending HTTP requests with jQuery and native web APIs

Nowadays, most developers use RESTful APIs to separate data sources from the presentation layer. jQuery offers a productive, shorthand function for getting JSON data from RESTful services, but native fetch() offers a better standard approach:

// jQuery
$.getJSON('https://jsonplaceholder.typicode.com/users')
.then(users => {
 console.log(users);
});

// Native
fetch('https://jsonplaceholder.typicode.com/users')
 .then(req => req.json())
 .then(users => {
   console.log(users);
 });
Enter fullscreen mode Exit fullscreen mode

Result:
Requesting JSON Data From A Restful Web Service With jQuery And Native Web APIs
Requesting JSON data from a RESTful web service with jQuery and native web APIs

Utility functions

jQuery offers various pre-developed utility functions to save web developers time. Nowadays, we can find inbuilt ECMAScript features for all of these pre-developed utility functions that exist in jQuery v4, as listed in the following table:

jQuery Native replacement
`$.each()` `Array.forEach()`
`$.extend()` `Object.assign() or the spread operator`
`$.inArray()` `Array.includes()`
`$.map()` `Array.map()`
`$.parseHTML()` `document.implementation.createHTMLDocument()`
`$.isEmptyObject()` `Object.keys()`
`$.merge()` `Array.concat()`

Older utilities like $.parseJSON() were already deprecated in past jQuery versions and removed in v4.

Can I use jQuery with Vue, React, or Angular?

Web developers used jQuery when modern app development frontend libraries didn’t exist. They used jQuery’s DOM manipulation and AJAX features mostly to dynamically update the frontend without refreshing the entire webpage. Now, SPA (single-page application) development techniques in modern frontend frameworks/libraries let web developers build highly interactive, well-structured, lightweight web apps without using old-fashioned AJAX-based rendering techniques.

We can use jQuery with Vue, React, and Angular like any popular frontend library/framework, but integrating jQuery with these frontend libraries is discouraged since it doesn’t bring any value to the modern frontend development ecosystem.

Every popular frontend library offers the ref concept for accessing DOM element references within components, so you don’t need to use either jQuery or document.querySelector(). For example, you can get the DOM element reference of a <div> in Vue as follows:

<script>
export default {
 mounted() {
   const elm = this.$refs.elm;
   console.log(elm);
 }
}
</script>

<template>
 <div ref="elm">Vue</div>
</template>
Enter fullscreen mode Exit fullscreen mode

Result:
Accessing DOM Element References In Vue Using Refs
Accessing DOM element references in Vue using refs

Using jQuery in Vue as follows is indeed possible, but it undermines the modern Vue source with old-fashioned syntax that was introduced about a decade ago and breaks the intended way a modern frontend library should be used:

<script>
import $ from 'jquery';

export default {
 mounted() {
   const elm = $('#elm');
   console.log(elm);
 }
}
</script>

<template>
 <div id="elm">Vue</div>
</template>
Enter fullscreen mode Exit fullscreen mode

Manual DOM manipulation rarely happens with modern frontend libraries like Vue. However, if you face such a situation, using native web APIs is the recommended approach.

Conclusion

jQuery was undoubtedly a remarkable JavaScript library that introduced a productive, developer-friendly approach to building web app frontends with DOM manipulation and AJAX techniques. jQuery gained popularity through browser compatibility issues and the lack of developer-focused features in native web APIs. W3C and ECMAScript solved these issues by introducing new web APIs and JavaScript language features.

The current state of web APIs offers better, modern, developer-friendly classes and functions for all features that jQuery possesses, making jQuery unnecessary in the modern web.

The recent v4 beta release of jQuery confirmed this with feature removals and enhancements focused on maintenance rather than innovation. V4 and other jQuery releases will most likely have more feature removals because of the availability of cross-browser native web APIs.

Upcoming versions may end support for older browsers since most users tend to use up-to-date browsers. I also think jQuery won’t become popular again since the current native web APIs are stable and standardized well, but developers who work with legacy web apps that depend on jQuery will continue to use it and upgrade their projects to jQuery v4, v5, and so on. All of that being said, nobody wants to increase web app bundle sizes by adding jQuery for development features that they can easily find in any popular web browser!


LogRocket: Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.

LogRocket Signup

LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free.

Top comments (3)

Collapse
 
damian_cyrus profile image
Damian Cyrus

Fantastic times as document.querySelector came into our world. The first thing I did was remove most of jQuery code wherever I could and to make others confused why it is still working fine for selectors:

var $ = document.querySelector;

const element = $('#id');
Enter fullscreen mode Exit fullscreen mode

Of course, it won't help a lot to transform all the jQuery functions, but for short selectors (in most cases) it was fine. Today, you might use a better name than $.

Collapse
 
philip_zhang_854092d88473 profile image
Philip

Your blog has taught me so much about modern webdev practices! EchoAPI’s API mocking is especially helpful for setting up backend simulations, so I can test UI elements faster.

Collapse
 
dominikx20pl profile image
Dominik

Are there any arguments for JQuery then?