In the world of web development, both jQuery and Vanilla JavaScript are widely used to create interactive and dynamic web pages. While jQuery simplifies many tasks with its concise syntax and powerful features, Vanilla JavaScript, the standard language of the web, has evolved significantly, offering similar capabilities with modern ES6+ features. In this article, we will compare jQuery vs. Vanilla JavaScript through over 25+ examples to help you decide and understand their differences and when to use each.
A complete Comparison of jQuery vs. Vanilla JavaScript
The debate between jQuery and vanilla JavaScript is frequently raised in the context of web development. Developers consider the advantages and disadvantages of creating pure JavaScript code versus utilizing a framework such as jQuery. jQuery makes it simpler for newbies to get started by streamlining numerous common tasks including DOM manipulation, event handling, and AJAX calls. Though it necessitates a deeper comprehension of the language, Vanilla JavaScript is more flexible and can result in improved performance because it does not require the overhead of an additional library. For you to make the best decisions possible for your projects, you must be aware of both the benefits and drawbacks of both approaches.
1. Selecting Elements
Selecting elements is a fundamental task in web development. jQuery simplifies this with its $ selector.
Using jQuery:
var element = $('#elementID');
Using Vanilla JS:
var element = document.getElementById('elementID');
With Vanilla JS, you use document.getElementById, which is straightforward and effective for selecting a single element by its ID.
2. Selecting Multiple Elements
Selecting multiple elements by class name is also common.
Using jQuery:
var elements = $('.className');
Using Vanilla JS:
var elements = document.querySelectorAll('.className');
document.querySelectorAll in Vanilla JS can select multiple elements, similar to jQuery’s class selector.
3. Adding a Class
Adding a class to an element changes its styling or behavior.
Using jQuery:
$('#elementID').addClass('newClass');
Using Vanilla JS:
document.getElementById('elementID').classList.add('newClass');
Using classList.add in Vanilla JS is the modern approach for manipulating classes.
4. Removing a Class
Removing a class is just as simple.
Using jQuery:
$('#elementID').removeClass('oldClass');
Using Vanilla JS:
document.getElementById('elementID').classList.remove('oldClass');
classList.remove provides a clean and readable way to remove classes.
5. Toggling a Class
Toggling a class can be useful for adding and removing classes based on a condition.
Using jQuery:
$('#elementID').toggleClass('toggleClass');
Using Vanilla JS:
document.getElementById('elementID').classList.toggle('toggleClass');
classList.toggle in Vanilla JS efficiently handles class toggling.
6. Setting CSS Properties
Changing the style of an element dynamically is a common requirement.
Using jQuery:
$('#elementID').css('color', 'red');
Using Vanilla JS:
document.getElementById('elementID').style.color = 'red';
Directly manipulating the style property is straightforward in Vanilla JS.
7. Getting CSS Properties
Sometimes you need to read the computed style of an element.
Using jQuery:
var color = $('#elementID').css('color');
Using Vanilla JS:
var color = window.getComputedStyle(document.getElementById('elementID')).color;
getComputedStyle allows you to read the current styles applied to an element.
8. Hiding an Element
Hiding elements is a common task in creating interactive web pages.
Using jQuery:
$('#elementID').hide();
Using Vanilla JS:
document.getElementById('elementID').style.display = 'none';
Setting display: none directly hides the element in Vanilla JS.
9. Showing an Element
Showing an element that was hidden.
Using jQuery:
$('#elementID').show();
Using Vanilla JS:
document.getElementById('elementID').style.display = 'block';
Restoring the display property shows the element again.
10. Fade Out Effect
Creating fade effects enhances user experience.
Using jQuery:
$('#elementID').fadeOut();
Using Vanilla JS:
document.getElementById('elementID').style.transition = 'opacity 0.5s';
document.getElementById('elementID').style.opacity = '0';
Using CSS transitions in Vanilla JS, you can create similar effects without jQuery.
11. Slide Up Effect
Sliding elements is another common UI effect.
Using jQuery:
$('#elementID').slideUp();
Using Vanilla JS:
document.getElementById('elementID').style.transition = 'height 0.5s';
document.getElementById('elementID').style.height = '0';
CSS transitions again help replicate the sliding effect in Vanilla JS.
12. Adding an Event Listener
Event handling is crucial for interactive applications.
Using jQuery:
$('#elementID').on('click', function() {
alert('Clicked!');
});
Using Vanilla JS:
document.getElementById('elementID').addEventListener('click', function() {
alert('Clicked!');
});
addEventListener is the standard way to bind events in Vanilla JS.
13. Removing an Event Listener
Detaching event handlers is necessary to prevent memory leaks and unwanted behavior.
Using jQuery:
$('#elementID').off('click');
Using Vanilla JS:
var element = document.getElementById('elementID');
function handleClick() {
alert('Clicked!');
}
element.addEventListener('click', handleClick);
element.removeEventListener('click', handleClick);
jQuery uses off to remove the click event, while Vanilla JS requires a reference to the handler.
14. AJAX GET Request
Fetching data asynchronously is essential for dynamic web applications.
Using jQuery:
$.get('https://api.example.com/data', function(data) {
console.log(data);
});
Using Vanilla JS:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
jQuery simplifies AJAX requests with $.get, whereas Vanilla JS uses the fetch API.
15. AJAX POST Request
Sending data asynchronously is as important as fetching it.
Using jQuery:
$.post('https://api.example.com/data', {key: 'value'}, function(response) {
console.log(response);
});
Using Vanilla JS:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({key: 'value'})
})
.then(response => response.json())
.then(data => console.log(data));
Both examples send a POST request, but Vanilla JS’s fetch API provides more control over the request.
16. Document Ready
Ensuring the DOM is fully loaded before executing code is crucial.
Using jQuery:
$(document).ready(function() {
console.log('DOM is ready!');
});
Using Vanilla JS:
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM is ready!');
});
jQuery’s ready method and Vanilla JS DOMContentLoaded event achieve the same result.
17. Appending HTML Content
Adding new content to a page dynamically is common in web development.
Using jQuery:
$('#elementID').append('<p>New content</p>');
Using Vanilla JS:
document.getElementById('elementID').insertAdjacentHTML('beforeend', '<p>New content</p>');
Both lines add a new paragraph to the element with ID elementID.
18. Prepending HTML Content
Adding content to the beginning of an element is also frequent.
Using jQuery:
$('#elementID').prepend('<p>New content</p>');
Using Vanilla JS:
document.getElementById('elementID').insertAdjacentHTML('afterbegin', '<p>New content</p>');
Both examples insert a paragraph at the beginning of the element with ID elementID.
19. Getting/Setting HTML Content
Reading and writing HTML content inside an element is fundamental.
Using jQuery:
var html = $('#elementID').html();
$('#elementID').html('New HTML content');
Using Vanilla JS:
var html = document.getElementById('elementID').innerHTML;
document.getElementById('elementID').innerHTML = 'New HTML content';
Both methods retrieve and set the inner HTML of the element with ID elementID.
20. Getting/Setting Text Content
Handling text content is as essential as handling HTML content.
Using jQuery:
var text = $('#elementID').text();
$('#elementID').text('New text content');
Using Vanilla JS:
var text = document.getElementById('elementID').textContent;
document.getElementById('elementID').textContent = 'New text content';
Both lines of code work with text content inside the element with ID elementID.
21. Cloning an Element
Cloning elements can be useful when you need to duplicate content dynamically.
Using jQuery:
var clone = $('#elementID').clone();
Using Vanilla JS:
var clone = document.getElementById('elementID').cloneNode(true);
Both methods clone the element with ID elementID, with cloneNode(true) in Vanilla JS to include child elements.
22. Removing an Element
Removing elements from the DOM is often necessary to manage dynamic content.
Using jQuery:
$('#elementID').remove();
Using Vanilla JS:
var element = document.getElementById('elementID');
element.parentNode.removeChild(element);
Both examples remove the element with ID elementID from the DOM.
23. Checking if an Element Exists
Checking for the existence of an element before manipulating it prevents errors.
Using jQuery:
if ($('#elementID').length) {
console.log('Element exists');
}
Using Vanilla JS:
if (document.getElementById('elementID')) {
console.log('Element exists');
}
Both methods check if the element with ID elementID exists.
24. Serializing Form Data
Serializing form data is useful for AJAX form submissions.
Using jQuery:
var formData = $('#formID').serialize();
Using Vanilla JS:
var form = document.getElementById('formID');
var formData = new URLSearchParams(new FormData(form)).toString();
Both examples serialize the form data, but Vanilla JavaScript uses FormData and URLSearchParams.
25. Debouncing Functions
Debouncing ensures that a function is not called too frequently, often used with resize or scroll events.
Using jQuery:
var debounce = function(func, delay) {
var timer;
return function() {
clearTimeout(timer);
timer = setTimeout(func, delay);
};
};
$(window).on('resize', debounce(function() {
console.log('Resized!');
}, 250));
Using Vanilla JS:
var debounce = function(func, delay) {
var timer;
return function() {
clearTimeout(timer);
timer = setTimeout(func, delay);
};
};
window.addEventListener('resize', debounce(function() {
console.log('Resized!');
}, 250));
Both examples debounce a function that logs a message when the window is resized.
26. Throttling Functions
Throttling limits the rate at which a function executes, useful for scroll or resize events.
Using jQuery:
var throttle = function(func, delay) {
var lastCall = 0;
return function() {
var now = (new Date()).getTime();
if (now - lastCall >= delay) {
lastCall = now;
func();
}
};
};
$(window).on('scroll', throttle(function() {
console.log('Scrolled!');
}, 250));
Using Vanilla JS:
var throttle = function(func, delay) {
var lastCall = 0;
return function() {
var now = (new Date()).getTime();
if (now - lastCall >= delay) {
lastCall = now;
func();
}
};
};
window.addEventListener('scroll', throttle(function() {
console.log('Scrolled!');
}, 250));
Both examples throttle a function that logs a message when the window is scrolled.
27. AJAX Error Handling
Using jQuery:
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.log('Error:', error);
}
});
Using Vanilla JS:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
28. Chaining Animations
Combining vanilla and jQuery animation chains While JavaScript can create comparable visual effects, the methods vary greatly in terms of readability, simplicity, and amount of code needed.
Using jQuery:
$('#elementID').slideUp(500).slideDown(500).fadeOut(500).fadeIn(500);
Using Vanilla JS:
var element = document.getElementById('elementID');
element.style.transition = 'all 0.5s';
element.style.height = '0';
setTimeout(() => {
element.style.height = 'auto';
element.style.opacity = '0';
setTimeout(() => {
element.style.opacity = '1';
}, 500);
}, 500);
Allows you to chain animations using built-in methods in a more simple and easily used way.
Conclusion
While jQuery simplifies many tasks with its concise syntax, Vanilla JavaScript has evolved to offer similar capabilities with modern ES6+ features. Understanding both allows developers to choose the best tool for the task at hand. For small projects or tasks requiring minimal DOM manipulation, Vanilla JavaScript may be sufficient. However, for larger projects with complex interactions, jQuery can significantly reduce development time and code complexity.