jQuery Mastery Guide
Complete guide from basics to advanced DOM manipulation
The Complete jQuery Mastery Guide
Master the library that revolutionized web development - DOM manipulation, events, AJAX, and animations made simple
Understanding jQuery: The Web's Most Popular JavaScript Library
jQuery is a fast, small, and feature-rich JavaScript library created by John Resig in 2006. It simplified HTML document traversal, event handling, animating, and Ajax interactions, making web development accessible to millions of developers.
What made jQuery revolutionary was its "write less, do more" philosophy. It abstracted browser inconsistencies and provided a consistent API that worked across all major browsers, solving one of the biggest pain points in early web development.
Historical Impact: At its peak, jQuery was used on over 70% of the top 1 million websites. While modern frameworks have gained popularity, jQuery remains essential for maintaining legacy codebases and is still widely used in WordPress themes, plugins, and many enterprise applications.
1. jQuery Basics & Selectors
Getting Started: Your First jQuery Script
<!-- Include jQuery in your HTML --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Basic HTML structure --> <div id="container"> <h1>Welcome to jQuery</h1> <button id="myButton">Click Me</button> <p class="description">This is a paragraph</p> </div> <script> // Wait for document to be ready $(document).ready(function() { // Your jQuery code here console.log("jQuery is ready!"); // Basic selector and action $('h1').css('color', 'blue'); $('#myButton').text('Click Me Now!'); $('.description').hide().fadeIn(1000); }); // Shorthand for document ready $(function() { // This is the same as $(document).ready() console.log("Document is ready (shorthand)"); }); </script>
jQuery Selectors: Finding Elements
$(function() { // Basic selectors $('#main'); // Element with id="main" $('.container'); // Elements with class="container" $('div'); // All div elements $('p.intro'); // Paragraphs with class="intro" // Multiple selectors $('h1, h2, h3'); // All h1, h2, and h3 elements $('div, .special'); // All divs and elements with class="special" // Hierarchy selectors $('#container p'); // All paragraphs inside #container $('#container > p'); // Direct child paragraphs of #container $('h1 + p'); // Paragraph immediately after h1 $('h1 ~ p'); // All paragraphs that are siblings of h1 // Attribute selectors $('input[type="text"]'); // Text inputs $('a[href^="https"]'); // Links starting with https $('img[src$=".jpg"]'); // Images ending with .jpg $('div[class*="box"]'); // Divs with "box" in class name // Form selectors $(':input'); // All input elements $(':text'); // Text inputs $(':checkbox'); // Checkboxes $(':radio'); // Radio buttons $(':submit'); // Submit buttons $(':disabled'); // Disabled elements $(':checked'); // Checked checkboxes/radios // Filter selectors $('li:first'); // First li element $('li:last'); // Last li element $('li:even'); // Even li elements $('li:odd'); // Odd li elements $('li:eq(2)'); // Third li element (0-based) $('li:gt(2)'); // li elements after index 2 $('li:lt(2)'); // li elements before index 2 $('div:has(p)'); // Divs that contain paragraphs $('div:not(.special)'); // Divs without class "special" // Content selectors $('div:contains("Hello")'); // Divs containing "Hello" $('div:empty'); // Empty divs $('div:parent'); // Divs that are parents // Visibility selectors $('div:visible'); // Visible divs $('div:hidden'); // Hidden divs });
DOM Traversal: Navigating the Document
$(function() { // Setup example DOM $('#container').html(\` <div class="parent"> <h1>Main Title</h1> <p class="first">First paragraph</p> <div class="child"> <span>Child content</span> <p>Inner paragraph</p> </div> <p class="last">Last paragraph</p> <ul> <li>Item 1</li> <li class="special">Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> </div> \`); // Parent/ancestor traversal $('.child').parent(); // Direct parent (.parent) $('.child').parents(); // All ancestors $('.child').parents('.parent'); // Ancestors with class .parent $('.child').closest('.parent'); // First ancestor matching selector // Child/descendant traversal $('.parent').children(); // Direct children $('.parent').children('p'); // Direct child paragraphs $('.parent').find('p'); // All descendant paragraphs $('.parent').find('.special'); // All descendants with class .special // Sibling traversal $('.first').next(); // Next sibling $('.first').next('p'); // Next sibling paragraph $('.first').nextAll(); // All following siblings $('.first').nextUntil('.last'); // Siblings until .last $('.last').prev(); // Previous sibling $('.last').prevAll(); // All previous siblings $('.last').prevUntil('.first'); // Siblings until .first $('.first').siblings(); // All siblings $('.first').siblings('p'); // All sibling paragraphs // Filtering elements $('li').first(); // First li $('li').last(); // Last li $('li').eq(1); // Second li (0-based) $('li').slice(1, 3); // li elements from index 1 to 2 $('li').filter('.special'); // li elements with class .special $('li').not('.special'); // li elements without class .special $('li').has('span'); // li elements that contain span // Chaining traversal methods $('.parent') .find('li') .first() .next() .addClass('highlight'); // End chaining and return to previous selection $('.parent') .find('li') .css('color', 'red') .end() // Returns to .parent selection .css('border', '1px solid blue'); });
Working with Selections
$(function() { // Creating a selection var $paragraphs = $('p'); var $headers = $('h1, h2, h3'); var $inputs = $('input[type="text"]'); // Checking selection properties console.log($paragraphs.length); // Number of elements in selection console.log($paragraphs.selector); // The selector string used // Accessing DOM elements from jQuery object var firstPara = $paragraphs[0]; // Native DOM element var firstPara = $paragraphs.get(0); // Same as above var allParas = $paragraphs.get(); // Array of all DOM elements // Converting DOM elements to jQuery objects var nativeElement = document.getElementById('main'); var $jqueryElement = $(nativeElement); // Iterating through selections $('li').each(function(index, element) { // 'this' refers to the current DOM element // 'element' is the same as 'this' console.log('Item ' + index + ': ' + $(this).text()); // Add class to every other item if (index % 2 === 0) { $(this).addClass('even'); } }); // Mapping selections to arrays var texts = $('li').map(function() { return $(this).text(); }).get(); console.log(texts); // Array of text contents // Filtering selections var longItems = $('li').filter(function() { return $(this).text().length > 10; }); var shortItems = $('li').not(function() { return $(this).text().length > 10; }); // Adding to selections var $allElements = $('div').add('p').add('span'); var $withContext = $('p').add('h1', document.getElementById('header')); // Checking if selection contains specific elements if ($paragraphs.is('.special')) { console.log('Selection contains .special elements'); } if ($paragraphs.has('.special').length) { console.log('Selection has descendants with .special'); } // Slicing selections var firstThree = $('li').slice(0, 3); var afterSecond = $('li').slice(2); // Utility methods var index = $('li').index($('.special')); // Index of .special in selection var $unique = $('div').add('p').add('div'); // Removes duplicates // Storing selections for performance var $cachedElements = $('#container .item'); // Reuse $cachedElements instead of reselecting });
2. DOM Manipulation
Getting and Setting Content
$(function() { // HTML content var htmlContent = $('#container').html(); // Get HTML $('#container').html('<p>New content</p>'); // Set HTML // Text content var textContent = $('p').text(); // Get text $('p').text('New text content'); // Set text // Form values var inputValue = $('input').val(); // Get value $('input').val('New value'); // Set value // Attributes var src = $('img').attr('src'); // Get attribute $('img').attr('src', 'new-image.jpg'); // Set attribute $('img').attr({ // Set multiple attributes 'src': 'new-image.jpg', 'alt': 'New image', 'title': 'Image title' }); $('img').removeAttr('alt'); // Remove attribute // CSS classes $('div').addClass('highlight'); // Add class $('div').removeClass('highlight'); // Remove class $('div').toggleClass('highlight'); // Toggle class $('div').hasClass('highlight'); // Check for class // CSS properties var color = $('div').css('color'); // Get CSS property $('div').css('color', 'red'); // Set CSS property $('div').css({ // Set multiple properties 'color': 'red', 'background-color': 'blue', 'font-size': '16px' }); // Dimensions var width = $('div').width(); // Content width var innerWidth = $('div').innerWidth(); // Content + padding var outerWidth = $('div').outerWidth(); // Content + padding + border var outerWidthFull = $('div').outerWidth(true); // + margin // Position var offset = $('div').offset(); // {top: X, left: Y} var position = $('div').position(); // Relative to offset parent var scrollTop = $('div').scrollTop(); // Scroll position // Data attributes $('div').data('key', 'value'); // Set data var value = $('div').data('key'); // Get data $('div').removeData('key'); // Remove data // Properties (for form elements) var isChecked = $('checkbox').prop('checked'); // Get property $('checkbox').prop('checked', true); // Set property $('checkbox').prop('disabled', true); // Disable element });
Creating and Modifying Elements
$(function() { // Creating new elements var $newDiv = $('<div>'); // Create div var $newPara = $('<p>Hello World</p>'); // Create p with content var $complexElement = $('<div class="box" data-id="123">Content</div>'); // Appending elements $('#container').append($newDiv); // Append to end $('#container').prepend($newDiv); // Prepend to beginning $('p').after($newDiv); // Insert after $('p').before($newDiv); // Insert before $newDiv.appendTo('#container'); // Append self to container $newDiv.prependTo('#container'); // Prepend self to container $newDiv.insertAfter('p'); // Insert self after p $newDiv.insertBefore('p'); // Insert self before p // Wrapping elements $('p').wrap('<div class="wrapper"></div>'); // Wrap each p individually $('p').wrapAll('<div class="wrapper"></div>'); // Wrap all p together $('p').wrapInner('<span class="inner"></span>'); // Wrap content of each p // Removing elements $('p').remove(); // Remove elements $('p').detach(); // Remove but keep data/events $('p').empty(); // Remove child elements // Cloning elements var $clone = $('p').clone(); // Clone without data/events var $cloneWithData = $('p').clone(true); // Clone with data/events var $cloneDeep = $('p').clone(true, true); // Clone with all data/events // Replacing elements $('p').replaceWith('<div>New content</div>'); // Replace each p $('<div>New content</div>').replaceAll('p'); // Replace all p with new content // Practical examples // Create a list dynamically var items = ['Apple', 'Banana', 'Orange']; var $list = $('<ul class="fruit-list">'); $.each(items, function(index, value) { $list.append($('<li>').text(value)); }); $('#container').append($list); // Create a table var data = [ ['John', 'Doe', '30'], ['Jane', 'Smith', '25'], ['Bob', 'Johnson', '35'] ]; var $table = $('<table class="data-table">'); var $thead = $('<thead>').appendTo($table); var $tbody = $('<tbody>').appendTo($table); // Add header $thead.append($('<tr>').append( $('<th>').text('First Name'), $('<th>').text('Last Name'), $('<th>').text('Age') )); // Add rows $.each(data, function(index, row) { var $tr = $('<tr>').appendTo($tbody); $.each(row, function(i, cell) { $tr.append($('<td>').text(cell)); }); }); $('#container').append($table); });
Advanced DOM Manipulation
$(function() { // Form manipulation $('form').serialize(); // Serialize form data $('form').serializeArray(); // Serialize as array of objects // Example: Dynamic form builder function createForm() { var $form = $('<form>').attr('id', 'user-form'); // Text input $form.append( $('<div class="form-group">').append( $('<label>').attr('for', 'name').text('Name:'), $('<input>').attr({ type: 'text', id: 'name', name: 'name', class: 'form-control', placeholder: 'Enter your name' }) ) ); // Email input $form.append( $('<div class="form-group">').append( $('<label>').attr('for', 'email').text('Email:'), $('<input>').attr({ type: 'email', id: 'email', name: 'email', class: 'form-control', placeholder: 'Enter your email' }) ) ); // Select dropdown var $select = $('<select>').attr({ id: 'country', name: 'country', class: 'form-control' }); var countries = ['USA', 'Canada', 'UK', 'Australia']; $.each(countries, function(index, country) { $select.append($('<option>').val(country).text(country)); }); $form.append( $('<div class="form-group">').append( $('<label>').attr('for', 'country').text('Country:'), $select ) ); // Submit button $form.append( $('<button>').attr({ type: 'submit', class: 'btn btn-primary' }).text('Submit') ); return $form; } $('#container').append(createForm()); // Advanced filtering and manipulation // Filter elements based on complex conditions var $longTexts = $('p').filter(function() { var text = $(this).text(); return text.length > 100 && text.indexOf('important') !== -1; }); // Batch operations with document fragments var $fragment = $(document.createDocumentFragment()); for (var i = 0; i < 100; i++) { $fragment.append($('<div>').text('Item ' + i)); } $('#container').append($fragment); // Performance optimization: cache selections var $cachedItems = $('.item'); // Instead of: // $('.item').css('color', 'red'); // $('.item').addClass('active'); // $('.item').fadeIn(); // Do this: $cachedItems .css('color', 'red') .addClass('active') .fadeIn(); // Chaining with callbacks $('.box') .fadeOut(500, function() { // Callback after fadeOut $(this).html('Content changed').fadeIn(500); }) .delay(1000) .slideUp(); // Working with large datasets function renderLargeList(items) { var $container = $('#list-container').empty(); var batchSize = 50; var currentIndex = 0; function renderBatch() { var batch = items.slice(currentIndex, currentIndex + batchSize); var $fragment = $(document.createDocumentFragment()); $.each(batch, function(index, item) { $fragment.append( $('<li>').addClass('list-item').text(item.name) ); }); $container.append($fragment); currentIndex += batchSize; if (currentIndex < items.length) { // Use setTimeout to avoid blocking the UI setTimeout(renderBatch, 0); } } renderBatch(); } });
3. Events & Effects
Event Handling
$(function() { // Basic event binding $('#myButton').click(function() { alert('Button clicked!'); }); $('input').focus(function() { $(this).css('background-color', 'yellow'); }); $('input').blur(function() { $(this).css('background-color', 'white'); }); // Using .on() method (recommended) $('#myButton').on('click', function() { console.log('Button clicked with .on()'); }); // Multiple events $('input').on('focus blur', function(event) { console.log('Event type: ' + event.type); }); // Event object $('a').on('click', function(event) { event.preventDefault(); // Prevent default action event.stopPropagation(); // Stop event bubbling console.log('Event target: ', event.target); console.log('Current target: ', event.currentTarget); }); // Event delegation (for dynamic content) $('#container').on('click', '.dynamic-item', function() { console.log('Dynamic item clicked: ' + $(this).text()); }); // One-time events $('#submit').one('click', function() { alert('This will only show once!'); }); // Namespaced events $('button').on('click.myNamespace', function() { console.log('Namespaced click event'); }); // Removing events $('button').off('click.myNamespace'); // Remove specific $('button').off(); // Remove all events // Common events $('form').on('submit', function(e) { e.preventDefault(); console.log('Form submitted'); }); $('input').on('change', function() { console.log('Input changed: ' + $(this).val()); }); $('input').on('keydown keyup keypress', function(e) { console.log('Key event: ' + e.type + ', Key: ' + e.key); }); $('.scrollable').on('scroll', function() { console.log('Scroll position: ' + $(this).scrollTop()); }); // Mouse events $('.item').on({ mouseenter: function() { $(this).addClass('hover'); }, mouseleave: function() { $(this).removeClass('hover'); }, mousedown: function() { $(this).addClass('active'); }, mouseup: function() { $(this).removeClass('active'); } }); // Custom events $('.element').on('customEvent', function(e, data) { console.log('Custom event with data: ', data); }); $('.element').trigger('customEvent', { message: 'Hello' }); // Event delegation example function setupEventDelegation() { var $container = $('#dynamic-container'); // This works for current AND future elements $container.on('click', '.item', function() { var $item = $(this); $item.toggleClass('selected'); console.log('Item selected: ' + $item.text()); }); // Add new items dynamically $('#add-item').on('click', function() { var itemCount = $container.find('.item').length; $container.append( $('<div>').addClass('item').text('Item ' + (itemCount + 1)) ); }); } setupEventDelegation(); });
Animations and Effects
$(function() { // Basic show/hide $('#element').hide(); // Hide immediately $('#element').show(); // Show immediately $('#element').toggle(); // Toggle visibility // Fading effects $('#element').fadeIn(1000); // Fade in over 1 second $('#element').fadeOut(500); // Fade out over 0.5 seconds $('#element').fadeToggle(800); // Toggle fade $('#element').fadeTo(1000, 0.5); // Fade to 50% opacity // Sliding effects $('#element').slideDown(1000); // Slide down $('#element').slideUp(500); // Slide up $('#element').slideToggle(800); // Toggle slide // Custom animations with .animate() $('#element').animate({ left: '+=100px', opacity: 0.5, fontSize: '24px' }, 1000, 'swing', function() { // Animation complete callback console.log('Animation finished!'); }); // Multiple animations in sequence $('#element') .animate({ left: '100px' }, 1000) .animate({ top: '100px' }, 1000) .animate({ left: '0px', top: '0px' }, 1000); // Stop animations $('#element').stop(); // Stop current animation $('#element').stop(true); // Stop and clear queue $('#element').stop(true, true); // Stop, clear queue, and jump to end // Delay animations $('#element') .fadeOut(500) .delay(1000) .fadeIn(500); // Animation queue control $('#element').queue(function(next) { // Custom queue function $(this).css('color', 'red'); next(); // Continue to next in queue }); // Practical animation examples // Accordion effect $('.accordion-header').on('click', function() { $(this).next('.accordion-content').slideToggle(300); $(this).toggleClass('active'); }); // Image slider function createSlider() { var $slider = $('.slider'); var $slides = $slider.find('.slide'); var currentSlide = 0; function showSlide(index) { $slides.stop().fadeOut(300); $slides.eq(index).fadeIn(300); } $('.next').on('click', function() { currentSlide = (currentSlide + 1) % $slides.length; showSlide(currentSlide); }); $('.prev').on('click', function() { currentSlide = (currentSlide - 1 + $slides.length) % $slides.length; showSlide(currentSlide); }); showSlide(currentSlide); } // Hover effects $('.card').on({ mouseenter: function() { $(this).stop().animate({ scale: 1.05, boxShadow: '0 10px 20px rgba(0,0,0,0.2)' }, 300); }, mouseleave: function() { $(this).stop().animate({ scale: 1, boxShadow: '0 2px 5px rgba(0,0,0,0.1)' }, 300); } }); // Loading spinner function showLoading() { $('#loading') .fadeIn(200) .delay(2000) .fadeOut(200); } // Progress bar animation function animateProgress(percent) { $('.progress-bar').animate({ width: percent + '%' }, 1000, 'easeOutCubic'); } // Staggered animations $('.stagger-item').each(function(index) { $(this).delay(index * 100).fadeIn(500); }); });
Advanced Event Patterns
$(function() { // Event namespaces for better management $('button').on('click.mymodule', function() { console.log('Module-specific click'); }); $('button').on('click.anothermodule', function() { console.log('Another module click'); }); // Remove only specific namespace events $('button').off('click.mymodule'); // Custom events with data $('.publisher').on('customMessage', function(e, data) { console.log('Received: ', data); }); $('.trigger').on('click', function() { $('.publisher').trigger('customMessage', { message: 'Hello World', timestamp: new Date() }); }); // Event delegation with filtering $('#table').on('click', 'td', function(e) { var $cell = $(this); var columnIndex = $cell.index(); if (e.shiftKey) { // Shift+click behavior $cell.toggleClass('selected-multiple'); } else if (e.ctrlKey) { // Ctrl+click behavior $cell.toggleClass('selected-additive'); } else { // Normal click behavior $cell.siblings().removeClass('selected'); $cell.addClass('selected'); } }); // Drag and drop simulation function setupDragDrop() { var $draggable = $('.draggable'); var isDragging = false; var startX, startY, initialX, initialY; $draggable.on('mousedown', function(e) { isDragging = true; var $this = $(this); startX = e.pageX; startY = e.pageY; initialX = parseInt($this.css('left')) || 0; initialY = parseInt($this.css('top')) || 0; $this.addClass('dragging'); e.preventDefault(); }); $(document).on('mousemove', function(e) { if (!isDragging) return; var deltaX = e.pageX - startX; var deltaY = e.pageY - startY; $draggable.css({ left: initialX + deltaX + 'px', top: initialY + deltaY + 'px' }); }); $(document).on('mouseup', function() { if (isDragging) { isDragging = false; $draggable.removeClass('dragging'); } }); } // Throttled events for performance function throttle(fn, delay) { var timer = null; return function() { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function() { fn.apply(context, args); }, delay); }; } $(window).on('scroll', throttle(function() { console.log('Throttled scroll event'); }, 250)); // Event-driven component communication var EventBus = $({}); // Component A publishes events $('.publisher').on('click', function() { EventBus.trigger('dataUpdated', { id: $(this).data('id'), action: 'click' }); }); // Component B subscribes to events EventBus.on('dataUpdated', function(e, data) { console.log('Component B received:', data); updateUI(data); }); // Complex form validation with events function setupFormValidation() { var $form = $('#user-form'); $form.on('blur', 'input[required]', function() { var $input = $(this); var value = $input.val().trim(); if (!value) { $input.addClass('error') .next('.error-message') .text('This field is required'); } else { $input.removeClass('error') .next('.error-message') .text(''); } }); $form.on('input', 'input[pattern]', function() { var $input = $(this); var pattern = new RegExp($input.attr('pattern')); var value = $input.val(); if (!pattern.test(value)) { $input.addClass('error'); } else { $input.removeClass('error'); } }); $form.on('submit', function(e) { var $errors = $(this).find('.error'); if ($errors.length > 0) { e.preventDefault(); $errors.first().focus(); alert('Please fix validation errors'); } }); } });
💻 jQuery Practice Projects
Beginner Level
- 1Build an Interactive Todo List with add/remove functionality
- 2Create an Image Gallery with lightbox effects
- 3Implement a Simple Form Validator with real-time feedback
- 4Build a Dynamic FAQ Accordion with smooth animations
- 5Create a Tabbed Interface with content switching
Intermediate Level
- 1Develop a Drag-and-drop Sortable List
- 2Build a Real-time Search Filter for large datasets
- 3Create a Custom Modal/Popup System
- 4Implement a Smooth Scrolling Navigation
- 5Build a Dynamic Data Table with sorting and pagination
Advanced Level
- 1Create a Single Page Application with jQuery
- 2Build a Custom jQuery Plugin from scratch
- 3Implement a Real-time Chat Interface
- 4Develop a Complex Form Wizard with validation
- 5Build an Interactive Dashboard with charts and widgets
📋 jQuery Quick Reference
Core Methods
- •$() - jQuery selector
- •ready() - Document ready
- •each() - Iterate elements
- •html() - Get/set HTML
- •text() - Get/set text
- •val() - Get/set values
- •attr() - Get/set attributes
Common Patterns
- •Event Delegation
- •Method Chaining
- •DOM Traversal
- •Animation Queues
- •AJAX Calls
- •Plugin Creation
- •Performance Optimization
Master the Library That Shaped the Web!
jQuery revolutionized web development by making JavaScript accessible to millions of developers. While modern frameworks have emerged, jQuery's simplicity, wide adoption, and extensive plugin ecosystem make it an invaluable tool for web development.
Understanding jQuery provides a solid foundation in DOM manipulation, event handling, and AJAX that translates well to modern JavaScript development. It remains essential for maintaining legacy codebases and is still widely used across the web.