All topics
Frontend · Learning hub

jQuery notes for developers

Master jQuery with a curated set of 2 developer notes — core concepts, patterns, and interview prep. Maintained by the DevRecall team.

Save this stack to your DevRecallMore Frontend notes
jQuery

DOM Manipulation & Events

jQuery: DOM Manipulation & Events jQuery is a fast, lightweight JavaScript library that simplifies DOM traversal, event handling, animation, and AJAX. Despite t

jQuery: DOM Manipulation & Events

jQuery is a fast, lightweight JavaScript library that simplifies DOM traversal, event handling, animation, and AJAX. Despite the rise of vanilla JS and modern frameworks, jQuery runs on a vast majority of websites and remains important in legacy codebases.

Setup & Selectors

<!-- CDN include -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<!-- Document ready -->
<script>
$(document).ready(function() {
    // DOM is ready — safe to manipulate
});

// Shorthand
$(function() {
    // same as document ready
});
</script>
// CSS-style selectors
$('#myId')             // by ID
$('.myClass')          // by class
$('p')                 // by tag
$('ul li')             // descendant
$('ul > li')           // direct child
$('input[type="text"]') // attribute
$('.parent .child')    // nested

// jQuery-specific selectors
$(':first')            // first matched
$(':last')             // last matched
$(':even'), $(':odd')  // 0-indexed
$(':not(.active)')     // negation
$(':contains("text")') // elements with text
$(':visible'), $(':hidden')
$(':checked'), $(':disabled'), $(':enabled')
$(':input')            // all form elements
$('tr:nth-child(2n)')  // every other row

// Finding relative elements
$('#parent').find('.child')   // descendants
$('.item').closest('.list')   // nearest ancestor
$('.item').siblings()         // siblings
$('.item').next()             // next sibling
$('.item').prev()             // previous sibling
$('.item').parent()           // direct parent
$('.item').parents('ul')      // all ancestor ul elements
$('.item:first').nextAll()    // all following siblings

DOM Manipulation

// Content
$('#title').text()             // get text content
$('#title').text('New Title')  // set text content
$('#box').html()               // get inner HTML
$('#box').html('<b>Bold</b>') // set inner HTML (use carefully — XSS risk)
$('input').val()               // get input value
$('input').val('new value')    // set input value

// Attributes & Properties
$('img').attr('src')                    // get attribute
$('img').attr('src', '/new.jpg')        // set attribute
$('img').attr({ src: '/img.jpg', alt: 'Photo' })  // set multiple
$('img').removeAttr('alt')
$(':checkbox').prop('checked')          // checked property
$(':checkbox').prop('checked', true)    // set property

// CSS
$('.box').css('color')                  // get
$('.box').css('color', 'red')           // set
$('.box').css({ color: 'red', fontSize: '16px' })  // multiple

// Classes
$('.item').addClass('active')
$('.item').removeClass('active')
$('.item').toggleClass('active')
$('.item').hasClass('active')           // returns boolean

// DOM insertion
$('#list').append('<li>Last item</li>')   // inside, at end
$('#list').prepend('<li>First</li>')      // inside, at start
$('.item').before('<p>Before</p>')        // outside, before
$('.item').after('<p>After</p>')          // outside, after
$('#container').html('<p>Replace all</p>') // replace contents

// Removal
$('.temp').remove()             // removes element + event handlers
$('.temp').detach()             // removes but keeps event handlers (reattach later)
$('.parent').empty()            // removes children

// Dimensions & Position
$('.box').width()               // content width
$('.box').outerWidth(true)      // includes margin
$('.box').height()
$('.box').offset()              // { top, left } relative to document
$('.box').position()            // relative to offset parent

Events

// Bind events
$('#btn').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log($(this).text());  // "this" = clicked element
});

// Shorthand methods
$('#btn').click(function() { ... });
$('#input').keyup(function(e) { console.log(e.key); });
$('#form').submit(function(e) { e.preventDefault(); });
$('.item').hover(
    function() { $(this).addClass('hovered'); },   // mouseenter
    function() { $(this).removeClass('hovered'); }  // mouseleave
);

// Event delegation (handles dynamically added elements)
$(document).on('click', '.dynamic-btn', function() {
    // works even for buttons added to DOM later
});
$('#list').on('click', 'li', function() {
    $(this).toggleClass('done');
});

// Unbind events
$('#btn').off('click');
$('#btn').off('click', specificHandler);

// Trigger events
$('#btn').trigger('click');
$('#form').trigger('submit');
$('#input').trigger('focus');

// Custom events
$(document).on('dataLoaded', function(e, data) {
    console.log(data);
});
$(document).trigger('dataLoaded', [{ items: [...] }]);
jQuery

AJAX, Animations & Plugins

jQuery: AJAX, Animations & Plugins AJAX // Full $.ajax $.ajax({ url: '/api/articles', method: 'GET', data: { page: 1, limit: 10 }, dataType: 'json', headers: {

jQuery: AJAX, Animations & Plugins

AJAX

// Full $.ajax
$.ajax({
    url: '/api/articles',
    method: 'GET',
    data: { page: 1, limit: 10 },
    dataType: 'json',
    headers: { 'Authorization': 'Bearer token' },
    success: function(data) {
        console.log(data);
    },
    error: function(xhr, status, error) {
        console.error(xhr.responseJSON?.message || error);
    },
    complete: function() {
        $('#spinner').hide();
    }
});

// Shorthand methods
$.get('/api/articles', { page: 1 }, function(data) {
    console.log(data);
});

$.post('/api/articles', { title: 'New', content: 'Body' }, function(data) {
    console.log('Created:', data);
});

$.getJSON('/api/users', function(users) {
    users.forEach(u => $('#list').append(`<li>${u.name}</li>`));
});

// Promise-based ($.ajax returns a Deferred)
$.ajax({ url: '/api/data' })
    .done(function(data) { /* success */ })
    .fail(function(xhr) { /* error */ })
    .always(function() { /* always runs */ });

// Serialize form data
var formData = $('#myForm').serialize();      // URL-encoded string
var formObj = $('#myForm').serializeArray(); // array of {name, value}

$.ajax({
    url: '/api/contact',
    method: 'POST',
    data: $('#myForm').serialize(),
    success: function() { alert('Sent!'); }
});

// Load HTML into element
$('#content').load('/partial.html #section', function() {
    console.log('Loaded');
});

Animations & Effects

// Show / Hide
$('.box').show();
$('.box').hide();
$('.box').toggle();

// Animated show/hide
$('.box').show(400);           // 400ms
$('.box').hide('slow');        // 'slow'=600ms, 'fast'=200ms
$('.box').fadeIn(300);
$('.box').fadeOut(300);
$('.box').fadeToggle();
$('.box').fadeTo(300, 0.5);   // fade to 50% opacity
$('.box').slideDown(400);
$('.box').slideUp(400);
$('.box').slideToggle();

// Custom animate
$('.box').animate({
    left: '+=100px',
    opacity: 0.5,
    height: '200px'
}, 600, 'swing', function() {
    // callback when done
});

// Stop / clear queue
$('.box').stop();              // stop current animation
$('.box').stop(true, true);   // clear queue + jump to end
$('.box').finish();           // complete all queued animations instantly

// Chaining
$('.box')
    .addClass('active')
    .fadeIn(300)
    .animate({ marginLeft: '20px' }, 200)
    .delay(1000)
    .fadeOut(300);

// Check animation state
if ($('.box').is(':animated')) { ... }

Utility Methods & Plugins

// Array/object utilities
$.each([1, 2, 3], function(index, value) {
    console.log(index, value);
});
$.each({ a: 1, b: 2 }, function(key, value) {
    console.log(key, value);
});

var doubled = $.map([1, 2, 3], function(val) { return val * 2; });
var evens = $.grep([1, 2, 3, 4], function(val) { return val % 2 === 0; });

$.extend({}, defaults, options);    // shallow merge
$.extend(true, {}, deep, merge);   // deep merge

// Type checking
$.isFunction(fn);
$.isArray(arr);
$.type(value);   // 'string', 'array', 'object', etc.

// DOM ready check
$.isReady   // boolean

// Writing a simple plugin
$.fn.highlight = function(color) {
    color = color || 'yellow';
    return this.each(function() {    // "this" = jQuery object
        $(this).css('background-color', color);
    });
};
// Usage: $('p').highlight('lightblue');

jQuery in 2024+

  • jQuery is still used on ~77% of all websites — you will encounter it in legacy codebases.

  • Modern vanilla alternatives: document.querySelector (selector), fetch (AJAX), classList (classes), element.addEventListener (events).

  • Do NOT add jQuery to new projects — use React/Vue/Svelte or vanilla JS instead.

  • If maintaining a jQuery codebase: upgrade to 3.x (dropped IE6-8), use $.ajax Promise API.

  • jQuery Migrate plugin: helps upgrade from 1.x/2.x to 3.x without breaking changes.

  • jQuery UI and jQuery Plugins: many are abandoned; prefer modern alternatives (Flatpickr, Select2, SortableJS).

  • Bundle size: 87KB minified (30KB gzip) — significant for modern performance budgets.

Keep your jQuery knowledge sharp.

Save this stack to your personal DevRecall — add your own notes, track what you're learning, and share what you know with the community.

Get started — free forever