jQuery & DOM Manipulation

jQuery vs Vanilla JavaScript

12 min Lesson 5 of 30

jQuery vs Vanilla JavaScript

Understanding the differences between jQuery and modern Vanilla JavaScript helps you choose the right tool for your project. In this lesson, we'll compare common tasks and see how both approaches work.

What is Vanilla JavaScript?

"Vanilla JavaScript" simply means pure JavaScript without any libraries or frameworks. Modern JavaScript (ES6+) has evolved significantly and now includes many features that made jQuery popular.

💡 Key Point: Modern browsers support powerful native JavaScript methods that can often replace jQuery. However, jQuery is still valuable for:
  • Rapid development and prototyping
  • Working with legacy codebases
  • Simplified syntax for common tasks
  • Cross-browser compatibility (older browsers)

Selecting Elements

By ID

jQuery:
var element = $('#myId');
Vanilla JavaScript:
var element = document.getElementById('myId');
// Or modern way:
var element = document.querySelector('#myId');

By Class

jQuery:
var elements = $('.myClass');
Vanilla JavaScript:
var elements = document.getElementsByClassName('myClass');
// Or modern way:
var elements = document.querySelectorAll('.myClass');

By Tag Name

jQuery:
var paragraphs = $('p');
Vanilla JavaScript:
var paragraphs = document.getElementsByTagName('p');
// Or modern way:
var paragraphs = document.querySelectorAll('p');

Complex Selectors

jQuery:
var items = $('#menu li.active');
Vanilla JavaScript:
var items = document.querySelectorAll('#menu li.active');
📝 Note: Modern JavaScript's querySelector() and querySelectorAll() use the same CSS selector syntax as jQuery, making the transition easier.

Manipulating Content

Getting/Setting Text

jQuery:
// Get text
var text = $('#myDiv').text();

// Set text
$('#myDiv').text('New text');
Vanilla JavaScript:
var element = document.querySelector('#myDiv');

// Get text
var text = element.textContent;

// Set text
element.textContent = 'New text';

Getting/Setting HTML

jQuery:
// Get HTML
var html = $('#myDiv').html();

// Set HTML
$('#myDiv').html('<strong>Bold text</strong>');
Vanilla JavaScript:
var element = document.querySelector('#myDiv');

// Get HTML
var html = element.innerHTML;

// Set HTML
element.innerHTML = '<strong>Bold text</strong>';

Getting/Setting Input Values

jQuery:
// Get value
var value = $('#username').val();

// Set value
$('#username').val('John Doe');
Vanilla JavaScript:
var input = document.querySelector('#username');

// Get value
var value = input.value;

// Set value
input.value = 'John Doe';

Modifying CSS

Single Property

jQuery:
$('#myDiv').css('color', 'red');
Vanilla JavaScript:
document.querySelector('#myDiv').style.color = 'red';

Multiple Properties

jQuery:
$('#myDiv').css({
    color: 'red',
    fontSize: '20px',
    backgroundColor: 'yellow'
});
Vanilla JavaScript:
var element = document.querySelector('#myDiv');
element.style.color = 'red';
element.style.fontSize = '20px';
element.style.backgroundColor = 'yellow';

// Or using Object.assign:
Object.assign(element.style, {
    color: 'red',
    fontSize: '20px',
    backgroundColor: 'yellow'
});

Working with Classes

jQuery:
// Add class
$('#myDiv').addClass('active');

// Remove class
$('#myDiv').removeClass('active');

// Toggle class
$('#myDiv').toggleClass('active');

// Check if has class
if ($('#myDiv').hasClass('active')) {
    // Do something
}
Vanilla JavaScript:
var element = document.querySelector('#myDiv');

// Add class
element.classList.add('active');

// Remove class
element.classList.remove('active');

// Toggle class
element.classList.toggle('active');

// Check if has class
if (element.classList.contains('active')) {
    // Do something
}
💡 Modern JavaScript Win: The classList API is just as clean and easy as jQuery for working with classes!

Event Handling

Click Events

jQuery:
$('#myButton').click(function() {
    alert('Clicked!');
});

// Or using on()
$('#myButton').on('click', function() {
    alert('Clicked!');
});
Vanilla JavaScript:
document.querySelector('#myButton').addEventListener('click', function() {
    alert('Clicked!');
});

Multiple Events

jQuery:
$('#myInput').on('focus blur change', function() {
    console.log('Event fired');
});
Vanilla JavaScript:
var input = document.querySelector('#myInput');
['focus', 'blur', 'change'].forEach(function(event) {
    input.addEventListener(event, function() {
        console.log('Event fired');
    });
});

Event Delegation

jQuery:
// Handle clicks on dynamically added items
$('#list').on('click', 'li', function() {
    console.log('List item clicked');
});
Vanilla JavaScript:
document.querySelector('#list').addEventListener('click', function(e) {
    if (e.target.tagName === 'LI') {
        console.log('List item clicked');
    }
});

Document Ready

jQuery:
$(function() {
    // DOM is ready
});

// Or
$(document).ready(function() {
    // DOM is ready
});
Vanilla JavaScript:
document.addEventListener('DOMContentLoaded', function() {
    // DOM is ready
});

// Or simpler modern approach (if script is at end of body):
// Just write your code - no need to wait

Show/Hide Elements

jQuery:
$('#myDiv').show();
$('#myDiv').hide();
$('#myDiv').toggle();
Vanilla JavaScript:
var element = document.querySelector('#myDiv');

// Show
element.style.display = 'block';

// Hide
element.style.display = 'none';

// Toggle
element.style.display = element.style.display === 'none' ? 'block' : 'none';

AJAX Requests

jQuery:
$.ajax({
    url: '/api/users',
    method: 'GET',
    success: function(data) {
        console.log(data);
    },
    error: function(error) {
        console.error(error);
    }
});

// Or shorthand
$.get('/api/users', function(data) {
    console.log(data);
});
Vanilla JavaScript (Fetch API):
fetch('/api/users')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });

// Or with async/await (modern)
async function getUsers() {
    try {
        const response = await fetch('/api/users');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

Iterating Over Elements

jQuery:
$('li').each(function(index, element) {
    console.log(index, $(element).text());
});
Vanilla JavaScript:
var items = document.querySelectorAll('li');
items.forEach(function(element, index) {
    console.log(index, element.textContent);
});

// Or modern arrow function
items.forEach((element, index) => {
    console.log(index, element.textContent);
});

Creating Elements

jQuery:
var newDiv = $('<div>', {
    class: 'my-class',
    text: 'Hello World'
});
$('body').append(newDiv);
Vanilla JavaScript:
var newDiv = document.createElement('div');
newDiv.className = 'my-class';
newDiv.textContent = 'Hello World';
document.body.appendChild(newDiv);

Real-World Comparison Example

Let's build a simple todo list with both approaches:

jQuery Version

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        $(function() {
            $('#addBtn').click(function() {
                var text = $('#taskInput').val();
                if (text) {
                    $('#taskList').append(
                        $('<li>').text(text)
                    );
                    $('#taskInput').val('');
                }
            });

            $('#taskList').on('click', 'li', function() {
                $(this).toggleClass('completed');
            });
        });
    </script>
    <style>
        .completed { text-decoration: line-through; }
    </style>
</head>
<body>
    <input id="taskInput" placeholder="Enter task">
    <button id="addBtn">Add</button>
    <ul id="taskList"></ul>
</body>
</html>

Vanilla JavaScript Version

<!DOCTYPE html>
<html>
<head>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var addBtn = document.querySelector('#addBtn');
            var taskInput = document.querySelector('#taskInput');
            var taskList = document.querySelector('#taskList');

            addBtn.addEventListener('click', function() {
                var text = taskInput.value;
                if (text) {
                    var li = document.createElement('li');
                    li.textContent = text;
                    taskList.appendChild(li);
                    taskInput.value = '';
                }
            });

            taskList.addEventListener('click', function(e) {
                if (e.target.tagName === 'LI') {
                    e.target.classList.toggle('completed');
                }
            });
        });
    </script>
    <style>
        .completed { text-decoration: line-through; }
    </style>
</head>
<body>
    <input id="taskInput" placeholder="Enter task">
    <button id="addBtn">Add</button>
    <ul id="taskList"></ul>
</body>
</html>

When to Use jQuery vs Vanilla JavaScript

Use jQuery When Use Vanilla JS When
Working with legacy projects Building modern, lightweight apps
Need cross-browser support for old browsers Only supporting modern browsers
Rapid prototyping Performance is critical
Using jQuery plugins Minimal dependencies needed
Team prefers jQuery Working with modern frameworks
💡 Best Practice: In new projects, consider Vanilla JavaScript first. Use jQuery only if:
  • You need extensive cross-browser compatibility
  • You're using jQuery plugins
  • Your team is more comfortable with jQuery
  • Rapid development speed is more important than minimal file size

Performance Comparison

File Size:
jQuery 3.7.1 (minified): ~87 KB
Vanilla JavaScript: 0 KB (built into browser)
Speed Comparison (selecting 1000 elements):
document.querySelectorAll('div'):  ~1-2ms
$('div'):                          ~3-5ms
📝 Note: Performance differences are often negligible for typical web applications. Choose based on your project needs, not just raw speed.
🎯 Challenge Exercise:

Create the same functionality using BOTH jQuery and Vanilla JavaScript:

  • A form with name and email inputs
  • Validate inputs (not empty, email format)
  • Display error messages
  • On success, display the data below the form

Compare the code length and complexity of both approaches.

💡 Hint

For email validation, use regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/

Summary

In this lesson, you learned:

  • Modern Vanilla JavaScript can do most of what jQuery does
  • querySelector/querySelectorAll use the same syntax as jQuery
  • classList API makes class manipulation easy
  • addEventListener is the modern event handling approach
  • Fetch API replaces jQuery.ajax() for modern browsers
  • jQuery is still valuable for legacy support and rapid development
  • Choose the right tool based on project requirements

Congratulations! You've completed Module 1: jQuery Fundamentals. You now understand jQuery syntax, selectors, and how it compares to Vanilla JavaScript. In the next module, we'll dive deeper into DOM manipulation and events!

ES
Edrees Salih
11 hours ago

We are still cooking the magic in the way!