Replacing jQuery with native JavaScript methods

Loading

Replacing jQuery with Native JavaScript Methods

Over the years, jQuery has been a dominant library in web development due to its ease of use, cross-browser compatibility, and concise syntax. However, with the advancements in modern JavaScript (ES6+), many features that jQuery provides are now natively available in JavaScript, making it possible to remove jQuery from projects to enhance performance and reduce dependencies.

In this comprehensive guide, we will explore how to replace commonly used jQuery functionalities with their vanilla JavaScript equivalents. We will cover:

  • Selecting Elements
  • Manipulating the DOM
  • Handling Events
  • AJAX Requests
  • Animations and Effects
  • Utility Functions
  • Other Useful Features

1. Selecting Elements

In jQuery, selecting elements is straightforward using $(), but in modern JavaScript, we use document.querySelector() and document.querySelectorAll().

jQuery

var element = $('.my-class'); // Selects all elements with class 'my-class'

Vanilla JavaScript

var element = document.querySelector('.my-class'); // Selects the first element with the class
var elements = document.querySelectorAll('.my-class'); // Selects all elements with the class

Selecting by ID

jQuery:

$('#my-id');

JavaScript:

document.getElementById('my-id');

Selecting by Tag Name

jQuery:

$('p');

JavaScript:

document.getElementsByTagName('p');

2. Manipulating the DOM

jQuery provides various methods like .html(), .text(), .append(), .remove(), etc., for manipulating the DOM.

Setting or Getting Inner HTML

jQuery:

$('.my-class').html('Hello World!');
var content = $('.my-class').html();

JavaScript:

document.querySelector('.my-class').innerHTML = 'Hello World!';
var content = document.querySelector('.my-class').innerHTML;

Setting or Getting Text Content

jQuery:

$('.my-class').text('Hello World!');

JavaScript:

document.querySelector('.my-class').textContent = 'Hello World!';

Appending Elements

jQuery:

$('.parent').append('<div class="child">Child Element</div>');

JavaScript:

let div = document.createElement('div');
div.className = 'child';
div.innerText = 'Child Element';
document.querySelector('.parent').appendChild(div);

Removing Elements

jQuery:

$('.child').remove();

JavaScript:

document.querySelector('.child').remove();

3. Handling Events

jQuery provides methods like .on(), .click(), and .hover() to handle events. Modern JavaScript uses addEventListener().

Click Event

jQuery:

$('#my-button').click(function() {
    alert('Button clicked!');
});

JavaScript:

document.getElementById('my-button').addEventListener('click', function() {
    alert('Button clicked!');
});

Hover Event

jQuery:

$('#my-div').hover(
    function() { console.log('Mouse Entered'); }, 
    function() { console.log('Mouse Left'); }
);

JavaScript:

let myDiv = document.getElementById('my-div');
myDiv.addEventListener('mouseenter', () => console.log('Mouse Entered'));
myDiv.addEventListener('mouseleave', () => console.log('Mouse Left'));

4. AJAX Requests

jQuery simplifies AJAX requests using .ajax(), .get(), and .post(), but JavaScript has the fetch() API.

Making an AJAX Request

jQuery:

$.ajax({
    url: 'https://api.example.com/data',
    method: 'GET',
    success: function(response) {
        console.log(response);
    },
    error: function(error) {
        console.error(error);
    }
});

JavaScript:

fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

POST Request

jQuery:

$.post('https://api.example.com/submit', { name: 'John Doe' }, function(response) {
    console.log(response);
});

JavaScript:

fetch('https://api.example.com/submit', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'John Doe' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

5. Animations and Effects

jQuery provides easy animations using .fadeIn(), .fadeOut(), .slideUp(), etc. In JavaScript, CSS animations or requestAnimationFrame() can be used.

Fade In

jQuery:

$('.box').fadeIn();

JavaScript:

let box = document.querySelector('.box');
box.style.transition = 'opacity 0.5s';
box.style.opacity = 1;

Slide Toggle

jQuery:

$('.box').slideToggle();

JavaScript:

let box = document.querySelector('.box');
box.style.transition = 'max-height 0.5s';
box.style.maxHeight = box.style.maxHeight === '0px' ? '200px' : '0px';

6. Utility Functions

jQuery has helper functions like $.each(), $.map(), and $.trim(), but native JavaScript has equivalents.

Looping Through Arrays

jQuery:

$.each([1, 2, 3], function(index, value) {
    console.log(index, value);
});

JavaScript:

[1, 2, 3].forEach((value, index) => console.log(index, value));

Trimming a String

jQuery:

$.trim('  Hello World  ');

JavaScript:

'  Hello World  '.trim();

7. Form Handling

Handling form submission and serialization in jQuery is easy using .serialize(), but JavaScript provides built-in methods.

Serialize Form Data

jQuery:

let formData = $('#myForm').serialize();

JavaScript:

let formData = new FormData(document.getElementById('myForm'));

Submit Form Using Fetch

jQuery:

$('#myForm').submit(function(e) {
    e.preventDefault();
    $.post('/submit', $(this).serialize(), function(response) {
        console.log(response);
    });
});

JavaScript:

document.getElementById('myForm').addEventListener('submit', function(e) {
    e.preventDefault();
    let formData = new FormData(this);
    fetch('/submit', { method: 'POST', body: formData })
    .then(response => response.json())
    .then(data => console.log(data));
});

Modern JavaScript has made jQuery largely unnecessary for most use cases. Native JavaScript provides cleaner, more efficient ways to achieve the same results. Removing jQuery reduces dependency size, improves performance, and aligns better with modern development standards.

By following these conversions, you can migrate an existing jQuery-based project to pure JavaScript while maintaining functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *