Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 56 ยท Practice and Review

jQuery Cheat Sheet

A one-page jQuery 3 cheat sheet with selectors, traversal, DOM changes, events, effects, AJAX and utilities, each next to its modern JavaScript equivalent.

This is the page to keep open in a tab while you work on a jQuery codebase. It does not teach; it reminds. Every table has three columns: the jQuery call, what it does, and the plain JavaScript you would write today. That third column is useful in two ways. When you maintain old code, it tells you what a line really does underneath. When you start new code, it shows you whether you need the library at all.

Everything here is for jQuery 3.7 (the examples load [email protected] from a CDN). Each section links to the lesson that explains the topic in depth. Two runnable examples at the end let you try the most common calls.

How to read this sheet

jQuery call The short form you will meet in existing code.
What it does One line, including the return value if it matters.
Modern JS The native equivalent for new code.

Getters return a value from the first element; setters change all matched elements and return the collection.

1 / 2

Setup and the ready event

HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
jQuery What it does Modern JavaScript
$(function () { ... }) Runs when the DOM is ready (always asynchronously in jQuery 3) document.addEventListener("DOMContentLoaded", fn) or <script defer>
$(window).on("load", fn) Runs after images and styles loaded window.addEventListener("load", fn)
$.noConflict() Gives the $ name back to another library Not needed
(function ($) { ... })(jQuery) Safe local $ alias for plugins and modules Use ES modules

See setup and document ready.

Selecting elements

jQuery What it does Modern JavaScript
$("#id") Element with that id (collection of 0 or 1) document.getElementById("id")
$(".cls"), $("tag") All matches, as a jQuery collection document.querySelectorAll(".cls")
$("a[href^='http']") Any CSS selector works The same selector with querySelectorAll
$("ul > li", context) or $(ctx).find("li") Search inside a context ctx.querySelectorAll("li")
$("a, p") Several selectors at once querySelectorAll("a, p")
$(el) Wrap a DOM node Not needed
$("<div>"), $("<a>", { href: "#" }) Create elements document.createElement("div")
$x[0], $x.get(0) The raw DOM element list[0]
$x.length Number of matches (0 if none) list.length
$x.get() A real array of the elements Array.from(list)

jQuery extensions such as :first, :eq(), :visible, :hidden, :checked (CSS has this one), :input and :contains() are slower: select with CSS first and then call .first(), .eq(), .filter(":visible"). See basic selectors, filter selectors and selector performance.

Filtering and traversal

jQuery What it does Modern JavaScript
.first(), .last(), .eq(i) Pick by position (eq(-1) counts from the end) list[0], list.at(-1) on an array
.filter(sel or fn) Keep members that match [...list].filter(el => el.matches(sel))
.not(sel or fn) Remove members that match [...list].filter(el => !el.matches(sel))
.has(sel) Keep those containing a match [...list].filter(el => el.querySelector(sel))
.is(sel) true if any member matches el.matches(sel)
.slice(a, b) Sub-range [...list].slice(a, b)
.parent() Direct parent el.parentElement
.parents(sel), .parentsUntil(sel) All ancestors, nearest first Loop on parentElement
.closest(sel) Nearest ancestor (or self) that matches el.closest(sel)
.children(sel) Direct children el.children
.find(sel) Descendants at any depth el.querySelectorAll(sel)
.siblings() Other children of the same parent [...el.parentElement.children].filter(c => c !== el)
.next(), .prev() Adjacent sibling el.nextElementSibling, el.previousElementSibling
.nextAll(), .prevAll() All following or preceding siblings Loop on nextElementSibling
.index() Position among siblings [...el.parentElement.children].indexOf(el)
.add(sel), .addBack(), .end() Extend the set, include previous set, step back in the chain Array spread and variables
.each(function (i, el) {}) Loop; this is the element; return false stops list.forEach((el, i) => {}) or for...of
.map(fn).get() Build an array from the results Array.from(list, fn)

See filtering methods, traversing up, traversing down and sideways and collections.

Content, attributes, data and CSS

jQuery What it does Modern JavaScript
.text() / .text(s) Get or set text (safe for untrusted data) el.textContent
.html() / .html(s) Get or set markup (never for untrusted data) el.innerHTML
.val() / .val(v) Value of a form control; array for a multiple select el.value
.attr(n) / .attr(n, v) Read or write an attribute (null removes) getAttribute, setAttribute
.removeAttr(n) Remove an attribute removeAttribute(n)
.prop(n) / .prop(n, v) Live state: checked, disabled, selected el.checked = true
.data(k) / .data(k, v) Cached data, seeded from data-* with type conversion el.dataset.camelKey (strings only)
.removeData(k) Delete cached data delete, or a WeakMap
.addClass(c), .removeClass(c) Add or remove classes el.classList.add(c), .remove(c)
.toggleClass(c, state) Toggle, or force with a boolean el.classList.toggle(c, state)
.hasClass(c) Does the first element have it? el.classList.contains(c)
.css("prop") Computed value getComputedStyle(el).prop
.css("prop", v), .css({ a: b }) Set inline style el.style.prop = v
.width(), .height() Content box size (no padding) el.getBoundingClientRect() or clientWidth
.innerWidth(), .outerWidth(true) Add padding, border, margin offsetWidth plus computed margins
.offset(), .position() Position in the document or in the offset parent getBoundingClientRect(), offsetTop
.scrollTop() Scroll position el.scrollTop or window.scrollY

See getting and setting content, attributes and properties, the data method, CSS and classes and dimensions and position.

Inserting, removing and copying

jQuery What it does Modern JavaScript
.append(x), .prepend(x) Insert inside, at the end or start el.append(x), el.prepend(x)
.before(x), .after(x) Insert outside, before or after el.before(x), el.after(x)
x.appendTo(t), .prependTo, .insertBefore, .insertAfter Same, with the operands swapped (returns x) t.append(x)
.remove() Remove from the DOM; also clears data and handlers el.remove()
.detach() Remove but keep data and handlers el.remove() and keep the variable
.empty() Remove all children el.replaceChildren()
.replaceWith(x), x.replaceAll(t) Swap elements el.replaceWith(x)
.wrap(h), .wrapAll, .wrapInner, .unwrap() Add or remove a wrapping element Create, insert and move manually
.clone(), .clone(true) Copy; true copies data and handlers el.cloneNode(true) (no handlers)

Inserting an element that already exists in the page moves it; to insert it in several places, clone it. See inserting content and removing and replacing.

Events

jQuery What it does Modern JavaScript
.on("click", fn) Add a handler (this is the element) el.addEventListener("click", fn)
.on("click", "li", fn) Delegated handler parent.addEventListener("click", e => { const li = e.target.closest("li"); if (li && parent.contains(li)) { ... } })
.on("click.ns", fn) and .off(".ns") Namespaced handlers AbortController signal option
.off("click", fn) Remove a handler removeEventListener("click", fn)
.one("click", fn) Run once addEventListener("click", fn, { once: true })
.on("mouseenter mouseleave", fn) Several events at once; .hover(in, out) is a shorthand Two listeners
.trigger("x", [a, b]) Fire an event and its default action, with extra data el.dispatchEvent(new CustomEvent("x", { detail, bubbles: true }))
.triggerHandler("x") Run handlers only; no bubbling, no default action Call the function directly
event.preventDefault() Cancel the default action Same
event.stopPropagation() Stop bubbling Same
return false Both of the above (in jQuery handlers) Not equivalent; call each method
event.target, event.currentTarget Origin and handler element Same names
event.which Deprecated key or button code event.key, event.button

Do not use .bind(), .delegate() and .live(): they are deprecated or removed. See handling events, event delegation, the event object and custom events.

Effects and animation

jQuery What it does Modern JavaScript
.show(), .hide(), .toggle() Display handling; optional duration and callback el.hidden = true/false, style.display
.fadeIn(), .fadeOut(), .fadeToggle(), .fadeTo(d, o) Animate opacity CSS transition on opacity
.slideDown(), .slideUp(), .slideToggle() Animate height CSS transition, <details> or el.animate()
.animate({ prop: value }, d, easing, cb) Animate numeric properties; "+=20" is relative el.animate(keyframes, { duration })
.stop(clearQueue, jumpToEnd) Stop the running animation animation.cancel() or finish()
.delay(ms) Pause the queue setTimeout or await
.queue(), .dequeue() Custom queue steps Promises with await animation.finished
$.fx.off = true Turn animations off globally (useful in tests) prefers-reduced-motion media query

See showing and hiding, fading and sliding, custom animations and the animation queue.

AJAX and promises

jQuery What it does Modern JavaScript
$.ajax({ url, method, data, dataType }) Full request; returns a jqXHR promise fetch(url, { method, body })
$.get(url, data), $.getJSON(url) Shorthand GET fetch(url).then(r => r.json())
$.post(url, data) Shorthand POST fetch(url, { method: "POST", body })
.load(url + " #frag") Fetch HTML into an element fetch then innerHTML (sanitize first)
.done(fn), .fail(fn), .always(fn) Success, failure and cleanup callbacks .then, .catch, .finally
.then(ok, err) Promises/A+ in jQuery 3 .then
$.when(a, b) Wait for all Promise.all([a, b])
$.Deferred() A controllable promise new Promise(...) or Promise.withResolvers()
$.param(obj) Object to query string new URLSearchParams(obj).toString()
form.serialize() URL-encoded form data new URLSearchParams(new FormData(form)).toString()
form.serializeArray() Array of { name, value } [...new FormData(form)]
$.ajaxSetup({}) Default settings (use sparingly) A wrapper function around fetch

See AJAX with $.ajax(), the shorthands, deferreds and promises and AJAX patterns.

Utilities

jQuery What it does Modern JavaScript
$.extend({}, a, b) Shallow merge into the first object { ...a, ...b }
$.extend(true, {}, a, b) Deep merge structuredClone plus a merge function
$.each(arr, fn) Loop over arrays and objects arr.forEach, Object.entries(obj)
$.map(arr, fn) Map; flattens returned arrays and drops null and undefined arr.flatMap(fn) (keeps null)
$.grep(arr, fn) Filter arr.filter(fn)
$.inArray(v, arr) Index or -1 arr.indexOf(v), arr.includes(v)
$.isArray(x) Deprecated Array.isArray(x)
$.trim(s) Deprecated s.trim()
$.parseJSON(s) Deprecated JSON.parse(s)
$.proxy(fn, ctx) Fix this fn.bind(ctx) or an arrow function
$.noop An empty function () => {}
$.now() Deprecated Date.now()

See utility functions. A plugin skeleton for reference:

JavaScript
(function ($) {
  $.fn.myPlugin = function (options) {
    var settings = $.extend({ color: "gold" }, options);
    return this.each(function () {
      $(this).css("background", settings.color);
    });
  };
})(jQuery);

More in writing your own plugin.

Try the common calls

The first example uses the selection, traversal and DOM calls on a small list and prints the results next to the call that produced them.

Cheat sheet in action: selecting, traversing, changing

The second example covers events, a custom event, a few utilities and a stand-in AJAX call with $.when. The button shows the effect calls.

Cheat sheet in action: events, utilities, promises

Gotchas worth remembering

  • Empty collections are truthy. Test .length, not the object.
  • Setters affect every matched element; most getters read only the first (.attr(), .val(), .css(), .data()). The exception is .text(), which joins the text of all of them.
  • .html() with user data is an XSS hole. Use .text(), or create elements with $("<a>", { text }).
  • Cache selections you reuse, and prefer a delegated handler on a stable parent for dynamic content.
  • Clean up. .remove() clears handlers and data; .detach() does not; namespaced .off(".name") removes a whole family of handlers.
  • $.each and .each pass (index, value), the reverse of the native forEach((value, index) => ...).
  • Check deprecation warnings with jQuery Migrate before upgrading, as described in what changed in jQuery 3.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which native JavaScript is the closest equivalent of $("#list").on("click", "li", fn)?

    Delegation is one listener on a parent that finds the matching descendant of the event target at event time.
  2. 2. What is the modern replacement for $.when(a, b)?

    $.when waits for all of its promises, as Promise.all does. Promise.race settles with the first one only.
  3. 3. What is the difference between .remove() and .detach()?

    Use .detach() when you plan to put the same element back, and .remove() when you are done with it.
  4. 4. For an input that the user has changed, which call returns the current value of its checked state?

    .prop() reads the live DOM property. .attr() would return the initial HTML attribute.

Summary

  • Each jQuery call maps to a short native equivalent: querySelectorAll, closest, classList, textContent, addEventListener, fetch and Promise.all.
  • Selection returns collections; getters read the first element, setters change all, and most methods return the collection for chaining.
  • Use .text() for untrusted content, .prop() for state, .attr() for real attributes and .on() with delegation for dynamic content.
  • Effects are queued; call .stop() before starting new ones, and prefer CSS transitions for simple visuals.
  • Avoid the deprecated helpers ($.trim, $.isArray, $.parseJSON, .bind, .delegate) in new code.

That completes the course. For an honest look at moving a codebase off jQuery, read From jQuery to modern JavaScript, and to build something real, revisit the projects.