jQuery Cheat Sheet
The jQuery 4 methods from the jQuery track, from selecting elements to AJAX, with the plain JavaScript equivalents at the end. Nothing here uses APIs that jQuery 4 removed, so it is safe to copy into new code.
Getting started Lesson
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script> | Loads jQuery 4; your own script goes after it |
$(() => { … }); | Runs your code when the DOM is ready |
jQuery(($) => { … }); | Ready handler that works in WordPress no-conflict mode |
$('.offer').hide(); | Select, then act on every match |
$('p').addClass('note').show(); | Most methods return the set, so you can chain |
$('.offer').length | How many elements matched (0 if none) |
$menu[0] or $menu.get(0) | The plain DOM element inside the set |
$(event.currentTarget) | Wraps a DOM element as a jQuery object |
$(document).ready(fn) still works but is deprecated – use $(fn).
Selectors Lesson
$('#cart') | The element with id="cart" |
$('.price') | Every element with class price |
$('ul > li') | Any CSS selector works, combinators included |
$('input[type="email"]') | Attribute selector |
$('#cart').find('.price') | Search only inside an element |
.first() .last() | First or last element of the set |
.eq(2) .eq(-1) | By zero-based index; negative counts from the end |
.even() .odd() | Elements at even or odd indexes (0, 2, 4…) |
.filter(':visible') | Narrow a set with a jQuery-only selector |
if ($('#banner').length) { … } | Checks whether anything matched |
$('#' + $.escapeSelector('order.42')) | Escapes special characters in an id |
Avoid the deprecated :first, :eq(), :even selectors – use the methods instead.
Events Lesson
$('#buy').on('click', handler); | Attaches an event handler |
$('#name').on('input change', handler); | One handler for several events |
$('#list').on('click', 'li', handler); | Delegation: works for items added later |
event.preventDefault(); | Cancels a link or form's default action |
$(event.currentTarget) | The element whose handler is running |
event.key === 'Enter' | Which key was pressed |
.one('click', handler) | Runs at most once per element |
.off('click') | Removes click handlers |
.on('click.menu', fn) .off('.menu') | Namespaces: remove only your own handlers |
.trigger('click') | Runs the handlers from code |
Prefer .on('click', fn) over the deprecated .click(fn) shorthand.
Get and set content Lesson
.text() | Gets the combined text of the matched elements |
.text('Saved') | Sets plain text – safe for user input |
.html('<b>Saved</b>') | Sets HTML; only for content you trust |
.val() | Value of the first form field |
.val('Chennai') | Sets a field's value |
.attr('href') | Reads an attribute as written in the HTML |
.attr('href', '/offers/') | Sets an attribute |
.removeAttr('title') | Removes an attribute |
.prop('checked') | Live state: true or false |
.prop('disabled', true) | Sets a property such as disabled |
.data('price') | Reads data-price; "499" → 499 |
.text((i, old) => old.toUpperCase()) | Sets each value from its old one |
Use .prop() for checked, selected and disabled; .attr() for other attributes.
CSS and classes Lesson
.addClass('is-active') | Adds one or more classes |
.removeClass('is-active') | Removes classes |
.toggleClass('is-open') | Adds if missing, removes if present |
.toggleClass('is-open', isOpen) | Adds when true, removes when false |
.hasClass('is-open') | true if any element has the class |
.css('color') | Computed value, e.g. rgb(29, 78, 216) |
.css('font-size', '20px') | Sets an inline style – always give the unit |
.css({ color: 'teal', fontSize: '20px' }) | Sets several styles at once |
.css('color', '') | Removes that inline style |
.css('--brand', '#0a7a3d') | Sets a CSS custom property |
.width() .innerWidth() .outerWidth() | Content / + padding / + border, in px |
.outerWidth(true) | Includes the margin too |
jQuery 4 adds px to plain numbers only for a few properties, such as width and margin.
Add and remove elements Lesson
$('<li>').text(name) | Creates an element with safe text |
$('<li>', { text: name, class: 'item' }) | Creates an element with properties |
.append(el) .prepend(el) | Adds as the last / first child |
.after(el) .before(el) | Adds as the next / previous sibling |
$('<li>').appendTo('#list') | The same as append, written the other way round |
.remove() | Removes elements, with their data and handlers |
.detach() | Removes but keeps data and handlers for reuse |
.empty() | Removes all children, keeps the element |
.clone() | Copies the elements |
.replaceWith('<p>Sold out</p>') | Swaps the elements for new content |
Traversing Lesson
.closest('.card') | Nearest ancestor that matches, starting with itself |
.find('.price') | Matching descendants at any depth |
.parent() .parents('section') | Direct parent / all matching ancestors |
.children('li') | Direct children only |
.siblings() | All other elements at the same level |
.next() .prev() | The next / previous sibling |
.is('.active') | true if any element matches |
.not('.done') | Removes matching elements from the set |
.each((i, el) => { … }) | Runs a function for each element |
.index() | Position among its siblings |
.end() | Goes back to the previous set in a chain |
Common pattern: $btn.addClass('active').siblings().removeClass('active').
Effects Lesson
.hide() .show() .toggle() | Instantly hide, show or switch |
.fadeIn(400) .fadeOut('slow') | Fade; time in ms or 'fast'/'slow' |
.fadeToggle() | Fades in or out |
.fadeTo(300, 0.5) | Fades to 50% opacity |
.slideDown() .slideUp() .slideToggle() | Animates the height |
.fadeOut(400, () => { … }) | Callback runs when the effect ends |
.slideUp().delay(1000).slideDown() | Effects queue up and run in order |
.stop(true) | Stops the current effect and clears the queue |
$.fx.off = true; | Turns all effects into instant changes |
Respect prefers-reduced-motion: set $.fx.off for people who ask for less motion.
animate() Lesson
.animate({ opacity: 0.5, left: '200px' }, 600) | Animates numeric CSS properties |
.animate({ width: '+=50px' }) | Relative change from the current value |
{ duration: 400, easing: 'linear' } | Options object; built-in easings: swing, linear |
.animate({ … }).animate({ … }) | Runs one after the other |
.animate({ … }, { queue: false }) | Runs at the same time as other animations |
.animate({ … }, 400, () => { … }) | Callback when finished |
$('html, body').animate({ scrollTop: 0 }, 500) | Smooth scroll to the top |
.finish() | Jumps all queued animations to their end |
.promise().done(() => { … }) | Runs once every element has finished |
Colours do not animate in core jQuery. Use a CSS transition and toggle a class instead.
AJAX Lesson
$.getJSON(url) | GET request, parses the JSON reply |
.done(data => { … }) | Runs on success |
.fail(xhr => { … }) | Runs on error; xhr.status has the code |
.always(() => { … }) | Runs either way – hide the loader here |
$.get(url) $.post(url, data) | Shortcuts for GET and POST |
$.ajax({ url, method: 'POST', data }) | Full control with a settings object |
dataType: 'json' | The format you expect back |
contentType: 'application/json' | The format you send; pair with JSON.stringify(data) |
timeout: 5000 | Gives up after 5 seconds |
const data = await $.getJSON(url); | Works with await; throws on failure |
$('#box').load('part.html') | Loads an HTML fragment into an element |
jQuery 4 no longer switches JSON requests to JSONP; use CORS or dataType: 'jsonp' on purpose.
Forms and validation Lesson
$('#signup').on('submit', e => { … }) | Listen on the form, not the button |
$('#name').val().trim() | Field value without extra spaces |
$('input[name="size"]:checked').val() | Value of the chosen radio button |
$('#terms').prop('checked') | true if the box is ticked |
$('#city').val() | Selected option's value |
.serialize() | → "name=Asha&city=Chennai", ready to send |
.serializeArray() | Array of { name, value } objects |
.attr('aria-invalid', 'true') | Tells screen readers the field has an error |
.trigger('focus') | Moves focus to the first problem field |
e.currentTarget.checkValidity() | Runs the browser's built-in checks |
$('#send').prop('disabled', true) | Stops double submits while sending |
Always validate again on the server; browser checks can be skipped.
jQuery vs plain JavaScript Lesson
$('.item') | document.querySelectorAll('.item') |
$(fn) | defer on the script, or DOMContentLoaded |
.on('click', fn) | el.addEventListener('click', fn) |
.addClass('x') .toggleClass('x') | el.classList.add('x') / .toggle('x') |
.text('Hi') | el.textContent = 'Hi' |
.attr('href', url) | el.setAttribute('href', url) |
.data('price') | el.dataset.price (always a string) |
.closest('.card') | el.closest('.card') |
.remove() | el.remove() |
$.getJSON(url) | fetch(url).then(res => res.json()) |
.fadeOut() | A CSS transition plus a class toggle |
jQuery acts on every match; with querySelectorAll you loop with forEach.