Learn jQuery from basics to advanced concepts with interactive examples and live coding playground.
🚀 Introduction to jQuery
What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
// Basic jQuery Setup
$(document).ready(function() {
// Your code here
console.log("jQuery is ready!");
});
// Shorthand version
$(function() {
console.log("Document is ready!");
});
// jQuery vs Vanilla JS
// Vanilla JavaScript:
document.addEventListener('DOMContentLoaded', function() {
// Code here
});
// jQuery equivalent:
$(function() {
// Same code, simpler syntax
});
Why Use jQuery?
Cross-browser compatibility - Works in all browsers
jQuery uses CSS-style selectors to find elements in the DOM.
// Basic Selectors
$('#id') // Select by ID
$('.class') // Select by class
$('element') // Select by tag name
$('*') // Select all elements
// Examples
$('#header') // Element with id="header"
$('.menu-item') // All elements with class="menu-item"
$('p') // All paragraph elements
$('div.container') // All divs with class="container"
// Multiple Selectors
$('h1, h2, h3') // All h1, h2, and h3 elements
$('.btn, .button') // Elements with class btn OR button
Hierarchy Selectors
Select elements based on their relationship to other elements.
// Hierarchy Selectors
$('parent > child') // Direct children
$('ancestor descendant') // All descendants
$('prev + next') // Next adjacent sibling
$('prev ~ siblings') // All following siblings
// Examples
$('ul > li') // Direct li children of ul
$('div p') // All p elements inside divs
$('h1 + p') // First p after h1
$('h2 ~ p') // All p elements after h2
// Finding Elements
$('#container').find('.item') // Find .item within #container
$('.parent').children('li') // Direct li children
$('li.selected').siblings() // All siblings of selected li
$('li:first').next() // Next sibling
$('li:last').prev() // Previous sibling
Attribute & Filter Selectors
Advanced selectors for more specific element selection.
// Attribute Selectors
$('[attribute]') // Has attribute
$('[attribute="value"]') // Attribute equals value
$('[attribute!="value"]') // Attribute not equal
$('[attribute^="value"]') // Attribute starts with
$('[attribute$="value"]') // Attribute ends with
$('[attribute*="value"]') // Attribute contains
$('[attribute~="value"]') // Attribute contains word
// Examples
$('[data-toggle]') // Has data-toggle attribute
$('input[type="text"]') // Text input fields
$('a[href^="https"]') // Links starting with https
$('img[src$=".jpg"]') // JPG images
$('div[class*="col-"]') // Bootstrap column classes
// Filter Selectors
$(':first') // First element
$(':last') // Last element
$(':even') // Even elements (0-indexed)
$(':odd') // Odd elements (0-indexed)
$(':eq(n)') // Element at index n
$(':gt(n)') // Elements after index n
$(':lt(n)') // Elements before index n
$(':not(selector)') // Elements not matching selector
$(':has(selector)') // Elements containing selector
// Form Selectors
$(':input') // All input elements
$(':text') // Text inputs
$(':password') // Password inputs
$(':radio') // Radio buttons
$(':checkbox') // Checkboxes
$(':selected') // Selected options
$(':checked') // Checked inputs
Try jQuery Selectors
Item 1
Item 2
Item 3 (Special)
Item 4
Item 5
🎮 jQuery Events
Event Methods
jQuery provides simple methods for handling events.
jQuery makes it easy to read and modify element content.
// Getting Content
var text = $('#element').text(); // Get text content
var html = $('#element').html(); // Get HTML content
var value = $('#input').val(); // Get form value
var attr = $('#img').attr('src'); // Get attribute
// Setting Content
$('#element').text('New text'); // Set text content
$('#element').html('New HTML'); // Set HTML content
$('#input').val('New value'); // Set form value
$('#img').attr('src', 'new.jpg'); // Set attribute
$('#img').attr({ // Set multiple attributes
'src': 'new.jpg',
'alt': 'New image'
});
// Removing Attributes
$('#img').removeAttr('src'); // Remove attribute
// CSS Classes
$('#element').addClass('active'); // Add class
$('#element').removeClass('inactive'); // Remove class
$('#element').toggleClass('active'); // Toggle class
$('#element').hasClass('active'); // Check if has class
// CSS Properties
$('#element').css('color', 'red'); // Set single property
$('#element').css({ // Set multiple properties
'color': 'red',
'background': 'blue',
'font-size': '20px'
});
var color = $('#element').css('color'); // Get property value
Adding and Removing Elements
Dynamically add, remove, or replace elements in the DOM.
// Creating Elements
var newDiv = $('
New div
'); // Create new element
var newPara = $('
', { // Create with properties
text: 'New paragraph',
class: 'my-class',
css: {color: 'red'}
});
// Appending Elements
$('#container').append(newDiv); // Insert at end
$('#container').prepend(newDiv); // Insert at beginning
$('#element').after(newDiv); // Insert after
$('#element').before(newDiv); // Insert before
// Inserting Elements
newDiv.appendTo('#container'); // Append to container
newDiv.prependTo('#container'); // Prepend to container
newDiv.insertAfter('#element'); // Insert after element
newDiv.insertBefore('#element'); // Insert before element
// Wrapping Elements
$('#element').wrap('
'); // Wrap element
$('.items').wrapAll(''); // Wrap all
$('#element').wrapInner(''); // Wrap inner content
// Removing Elements
$('#element').remove(); // Remove element
$('#element').empty(); // Remove children only
$('#element').detach(); // Remove but keep data
// Replacing Elements
$('#old').replaceWith(newDiv); // Replace element
newDiv.replaceAll('#old'); // Replace all matching
// Cloning Elements
var clone = $('#element').clone(); // Clone element
var cloneWithData = $('#element').clone(true); // Clone with data and events
Traversing the DOM
Navigate through the DOM tree easily.
// Parent Elements
$('#child').parent(); // Immediate parent
$('#child').parents('div'); // All parent divs
$('#child').parentsUntil('#container'); // Parents until container
$('#child').closest('div'); // Closest parent div
// Child Elements
$('#parent').children(); // All children
$('#parent').children('.selected'); // Selected children
$('#parent').find('.item'); // Find descendants
// Sibling Elements
$('#element').siblings(); // All siblings
$('#element').siblings('.selected'); // Selected siblings
$('#element').next(); // Next sibling
$('#element').nextAll(); // All next siblings
$('#element').nextUntil('.stop'); // Next until selector
$('#element').prev(); // Previous sibling
$('#element').prevAll(); // All previous siblings
$('#element').prevUntil('.stop'); // Previous until selector
// Filtering Elements
$('div').first(); // First div
$('div').last(); // Last div
$('div').eq(2); // Div at index 2
$('div').slice(1, 3); // Divs 1 to 3
$('div').filter('.selected'); // Filter by selector
$('div').not('.hidden'); // Exclude elements
$('div').has('span'); // Divs containing span
// Chaining Traversal
$('#container')
.find('.item')
.first()
.next()
.addClass('active');
// Type Checking
$.isArray([1,2,3]); // true
$.isFunction(function() {}); // true
$.isNumeric('123'); // true
$.type('hello'); // "string"
$.isPlainObject({}); // true
$.isEmptyObject({}); // true
// Array/Object Operations
var arr = $.makeArray(arrayLike); // Convert to array
var merged = $.extend({}, obj1, obj2); // Merge objects
var cloned = $.extend(true, {}, obj); // Deep clone
var filtered = $.grep(array, function(item) {
return item > 10;
}); // Filter array
$.each(array, function(index, value) {
console.log(index, value);
}); // Iterate array/object
var mapped = $.map(array, function(item) {
return item * 2;
}); // Map array
// String Operations
var trimmed = $.trim(' hello '); // Trim whitespace
var paramStr = $.param({id: 1, name: 'John'}); // Object to query string
// Browser Detection (Deprecated but useful)
$.browser.webkit; // WebKit browser
$.browser.msie; // Internet Explorer
$.browser.version; // Browser version
// Support Detection
$.support.ajax; // AJAX support
$.support.boxModel; // Box model support
// Queue Management
$('#element').queue('fx', function(next) {
// Animation queue
next();
});
$('#element').dequeue('fx'); // Run next in queue
$('#element').clearQueue('fx'); // Clear queue
Data Storage
Store arbitrary data associated with DOM elements.
// Store data on elements
$('#element').data('key', 'value'); // Store data
var value = $('#element').data('key'); // Retrieve data
$('#element').data({ // Store multiple
name: 'John',
age: 30
});
// Check if data exists
var hasData = $('#element').hasData('key');
// Remove data
$('#element').removeData('key'); // Remove specific
$('#element').removeData(); // Remove all
// Data vs Attr
$('#element').data('custom', 'value'); // Stores in memory
$('#element').attr('data-custom', 'value'); // Stores as attribute
// Namespaced data
$('#element').data('user.name', 'John');
$('#element').data('user.age', 30);
// Data with objects
var user = {name: 'John', age: 30};
$('#element').data('user', user);
user.name = 'Jane'; // Modifies stored data too!
🧩 jQuery Plugins
Using Plugins
Thousands of plugins extend jQuery's functionality.