Interview Q&A · 42 questions · 18 answered publicly

jQuery Interview Questions

Ordered by how often they're asked. Sign in free to see every answer, rate your confidence and run timed mock interviews.

  1. Most asked What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?

    Summary

    $(fn) (the recommended form of $(document).ready(fn)) runs when the DOM is parsed, like DOMContentLoaded, before images and stylesheets finish loading. window.onload (or $(window).on('load', fn)) waits for every resource, including images and iframes. jQuery's ready handler also runs immediately if the DOM is already ready when it is registered.

    Longer Answer

    Use the ready handler for setting up event handlers and DOM work; use the load event only when you need image dimensions or fully loaded resources. Scripts loaded at the end of <body> or with defer run after parsing anyway, so they often do not need a ready wrapper at all. Since jQuery 3, ready handlers run asynchronously, and the $(document).on('ready', fn) form was removed.

    Code Example

    $(function () {
      // DOM is ready: safe to query elements and bind events
      $("#save").on("click", save);
    });
    

    Key Points

    • $(fn) = DOM ready.
    • window load = all resources.
    • Ready runs immediately if already ready.
    • defer scripts may not need it.

    Permalink

  2. Most asked What is event delegation, and why is it useful?

    Summary

    Event delegation attaches one handler to a parent element and lets events from children bubble up to it; jQuery's .on(event, selector, handler) runs the handler only when the event came from an element matching the selector. It works for elements added later and uses far fewer handlers than binding to every child.

    Longer Answer

    // Works for rows added after this line runs, with a single handler
    $("#orders").on("click", ".delete-order", function (e) {
      e.preventDefault();
      const id = $(this).data("id");
      deleteOrder(id);
    });
    

    Inside the handler, this is the matched child element, not the parent. Delegate to the closest stable container rather than document (bubbling all the way up costs time on every event and makes behaviour hard to trace). Events that do not bubble (such as focus; use focusin) need care.

    Key Points

    • One handler on a parent.
    • Works for future elements.
    • this = matched child.
    • Delegate to the nearest stable container.

    Deep dive: Code Clinic: review a jQuery shopping cart script

    Permalink

  3. Most asked What is the difference between .html() and .text(), and why does it matter for security?

    Summary

    .html(value) parses the value as HTML and inserts the resulting elements; .text(value) inserts it as plain text, escaping < and &. Passing user-controlled data to .html() (or .append(), .prepend(), .after() with an HTML string, or $(htmlString)) creates cross-site scripting vulnerabilities.

    Longer Answer

    A product review containing <img src=x onerror="stealCookies()"> executes when inserted with .html(). Use .text() for user data, build elements with $("<li>").text(name), and set attributes with .attr() / .prop(). When you must render user-provided HTML (rich text), sanitise it with an allow-list library such as DOMPurify first.

    Code Example

    // Unsafe: item.name could contain markup
    $list.append("<li>" + item.name + "</li>");
    
    // Safe
    $("<li>").text(item.name).appendTo($list);
    

    Key Points

    • .html() parses HTML; .text() escapes.
    • User data into .html()/.append() strings = XSS.
    • Build elements with .text()/.attr().
    • Sanitise rich text with DOMPurify.

    Deep dive: Code Clinic: review a jQuery shopping cart script

    Permalink

  4. Most asked How do you make AJAX requests with jQuery?

    Summary

    $.ajax({...}) is the general method; shorthands include $.get, $.post and $.getJSON. They return a jqXHR object that implements the Promise interface, so you chain .done(), .fail(), .always() or .then().

    Longer Answer

    $.ajax({
      url: "/api/orders",
      method: "POST",
      contentType: "application/json",
      data: JSON.stringify({ items }),
      dataType: "json",
      timeout: 10000,
    })
      .done((order) => showConfirmation(order))
      .fail((xhr) => showError(xhr.status, xhr.responseJSON))
      .always(() => $submit.prop("disabled", false));
    

    Notes: by default data objects are form-encoded, so set contentType and stringify for JSON APIs; set a timeout; handle failures visibly; and send the CSRF token for state-changing requests. The success/error callbacks still work, but the promise style composes better.

    Key Points

    • $.ajax and shorthands.
    • jqXHR is promise-like: done/fail/always/then.
    • JSON needs contentType + stringify.
    • Timeouts, errors, CSRF.

    Permalink

  5. Most asked What is jQuery, and is it still relevant today?

    Summary

    jQuery is a JavaScript library (first released in 2006) that simplified DOM selection and manipulation, events, animation and AJAX, and smoothed over browser inconsistencies. Modern browsers now provide most of this natively (querySelectorAll, classList, fetch, addEventListener), so new projects rarely need it, but it still runs on a large share of existing websites, including WordPress themes and many legacy business applications.

    Longer Answer

    Where jQuery remains relevant: maintaining and extending legacy applications, CMS ecosystems (WordPress, Drupal and their plugins), and small enhancements on server-rendered pages where adding a framework would be overkill. In interviews it usually signals a role that maintains an existing codebase, so expect questions about safe maintenance, performance, security updates and gradual migration.

    For new interactive applications teams typically choose a component framework (React, Vue, Svelte) or lightweight progressive-enhancement tools (Alpine.js, htmx).

    Key Points

    • DOM, events, AJAX, animation helper library.
    • Browsers now cover most of it natively.
    • Still common in legacy apps and CMSs.
    • Maintenance and migration skills matter.

    Permalink

  6. Most asked How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?

    Summary

    Use .on() to attach handlers and .off() to remove them, and .one() for handlers that should run once. .bind(), .unbind(), .delegate() and .undelegate() were deprecated in jQuery 3.0, and .live() was removed in 1.9; .on() replaces all of them, including delegated handling.

    Longer Answer

    $("#menu").on("click", ".item", onItemClick);   // delegated
    $(window).on("resize.layout", relayout);        // namespaced
    $(window).off("resize.layout");                 // remove only ours
    

    Shorthands such as .click(fn) still work but are deprecated in favour of .on("click", fn) in recent versions. To remove a specific handler, pass the same function reference to .off(), or use a namespace.

    Key Points

    • .on() / .off() / .one().
    • bind/delegate deprecated; live removed.
    • Same function reference or namespace to remove.
    • Shorthand methods deprecated.

    Permalink

  7. Most asked What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?

    Summary

    event.preventDefault() stops the browser's default action (following a link, submitting a form); event.stopPropagation() stops the event bubbling to ancestor handlers; returning false from a jQuery handler does both.

    Longer Answer

    Prefer calling preventDefault() explicitly: return false also stops propagation, which silently breaks delegated handlers and analytics listeners higher up the tree. stopImmediatePropagation() additionally prevents other handlers on the same element from running. In plain DOM addEventListener handlers, return false does nothing.

    Key Points

    • preventDefault: no default action.
    • stopPropagation: no bubbling.
    • return false: both (jQuery only).
    • Prefer explicit preventDefault.

    Permalink

  8. Most asked What is the difference between .attr() and .prop()?

    Summary

    .attr() reads and writes HTML attributes (the markup); .prop() reads and writes DOM properties (the live state of the element). For state such as checked, selected, disabled and value, use .prop(): the attribute holds the initial value, while the property reflects what the user did.

    Longer Answer

    $("#agree").attr("checked") may return "checked" or undefined based on the original markup even after the user unticks the box; $("#agree").prop("checked") returns the current boolean. Use .attr() for things like href, data-* (or .data()), aria-* and custom attributes. This distinction was introduced in jQuery 1.6 and is a common source of bugs in older code.

    Key Points

    • attr = HTML attribute; prop = live DOM property.
    • Use prop for checked/selected/disabled.
    • attr for href, aria-*, custom attributes.

    Permalink

  9. Most asked What are jQuery Deferreds, and how do you wait for several requests?

    Summary

    A Deferred is jQuery's promise implementation: it can be resolved or rejected, and handlers attach with .done(), .fail(), .always() and .then(). $.when(a, b) waits for several deferreds (such as AJAX calls) and resolves when all succeed, or rejects as soon as one fails.

    Longer Answer

    $.when($.getJSON("/api/user"), $.getJSON("/api/orders"))
      .done(([user], [orders]) => render(user, orders))
      .fail(() => showError());
    

    Each AJAX argument resolves with an array [data, textStatus, jqXHR], hence the destructuring. You can create your own with $.Deferred() to wrap callback APIs. In modern code, Promise.all and async/await work with jqXHR objects too, because since jQuery 3 they are Promises/A+ compatible.

    Key Points

    • Deferred = jQuery promises.
    • $.when for parallel waits.
    • AJAX resolves with [data, status, xhr].
    • Interoperates with native promises in 3.x.

    Permalink

  10. Most asked What does $.extend() do, and what is the prototype pollution risk?

    Summary

    $.extend(target, ...sources) copies properties from source objects into the target (a shallow merge); $.extend(true, target, ...sources) merges deeply. A deep merge of untrusted input in older jQuery versions could set properties on Object.prototype through a __proto__ key (CVE-2019-11358, fixed in jQuery 3.4.0), polluting every object in the page.

    Longer Answer

    Prototype pollution can bypass checks (if (user.isAdmin) becomes true for every object) or enable XSS through gadgets in other libraries. Keep jQuery up to date, never deep-merge untrusted JSON into configuration objects, and for copying data prefer structuredClone or the spread operator ({ ...defaults, ...options }) for shallow merges.

    Key Points

    • Shallow by default; true = deep.
    • Deep merging untrusted input polluted prototypes (fixed in 3.4.0).
    • Update jQuery; avoid merging untrusted data.
    • Spread/structuredClone in modern code.

    Permalink

  11. Most asked How do you improve the performance of jQuery-heavy pages?

    Summary

    Cache selections, scope queries, use event delegation instead of thousands of handlers, batch DOM changes (build off-DOM, insert once), avoid layout thrashing (separate reads such as .height() from writes), debounce or throttle scroll and resize handlers, prefer CSS transitions, and load only the plugins you use.

    Longer Answer

    For large manipulations, .detach() an element, modify it, and reattach it to avoid repeated reflows. Measure with the browser's Performance panel: long tasks from jQuery code usually come from repeated querying in loops, inserting elements one by one, or synchronous AJAX. Upgrading old jQuery versions also brings performance improvements.

    Key Points

    • Cache and scope selectors.
    • Delegate events.
    • Batch DOM writes; avoid thrashing.
    • Debounce scroll/resize.

    Permalink

  12. Most asked What is the difference between .remove(), .detach() and .empty(), and how do you avoid memory leaks?

    Summary

    .remove() removes elements and also their jQuery data and event handlers; .detach() removes elements but keeps data and handlers so you can reinsert them; .empty() removes all child nodes (and their data and handlers) but keeps the element.

    Longer Answer

    Memory leaks in jQuery pages usually come from: removing elements with native DOM methods (or innerHTML = ...), which leaves jQuery's data and handlers in memory; handlers bound on window or document by widgets that are never destroyed; and closures referencing large detached DOM trees. Use jQuery's removal methods for elements managed by jQuery, unbind global handlers on teardown (namespaces help), and check heap snapshots for detached DOM nodes.

    Key Points

    • remove: elements + data + handlers.
    • detach: keeps data and handlers.
    • empty: removes children.
    • Native removal can leak jQuery data.

    Deep dive: Code Clinic: review a jQuery shopping cart script

    Permalink

  13. Most asked How do you upgrade an old jQuery version safely?

    Summary

    Inventory the jQuery version and plugins in use, add the jQuery Migrate plugin (which restores removed APIs and logs warnings for deprecated usage), upgrade to the latest jQuery 3.x, fix every warning in development and testing, then remove Migrate.

    Longer Answer

    Main breaking areas from 1.x/2.x to 3.x: removed .size(), .load()/.unload()/.error() event shorthands; deprecated .bind() and .delegate(); asynchronous ready handlers; Promises/A+ behaviour of .then(); and stricter selector and HTML parsing. jQuery 4 continues by removing long-deprecated utilities (such as $.trim, $.isArray, $.parseJSON) and dropping very old browsers. Old plugins are the usual blocker; replace unmaintained ones. Upgrading matters because older versions have known XSS vulnerabilities.

    Key Points

    • Inventory versions and plugins.
    • jQuery Migrate to find deprecated usage.
    • Upgrade, fix warnings, remove Migrate.
    • Old plugins are the main blocker.

    Permalink

  14. Most asked Which security issues have affected jQuery, and how do you protect a legacy site?

    Summary

    Notable issues: XSS through HTML passed to DOM-manipulation methods in versions before 3.5.0 (CVE-2020-11022 and CVE-2020-11023, around htmlPrefilter), prototype pollution in $.extend(true, ...) before 3.4.0 (CVE-2019-11358), and older XSS issues in selector handling and cross-domain AJAX. Many sites still load vulnerable versions.

    Longer Answer

    Protection: upgrade to the latest jQuery 3.x, check plugins too (they often bundle old copies), never pass untrusted strings to .html(), $(html) or .append(), add a Content Security Policy, and scan dependencies regularly (npm audit, Retire.js, Snyk, or the browser extension that flags vulnerable libraries). Penetration testers and automated scanners flag old jQuery versions immediately.

    Key Points

    • XSS fixes in 3.5.0; prototype pollution fix in 3.4.0.
    • Upgrade jQuery and plugins.
    • No untrusted HTML into DOM methods.
    • CSP and dependency scanning.

    Deep dive: Code Clinic: review a jQuery shopping cart script

    Permalink

  15. Most asked How would you migrate a codebase from jQuery to plain JavaScript or a framework?

    Summary

    Incrementally: stop adding new jQuery code, replace jQuery utilities with native equivalents module by module (selectors, classList, fetch, events), and move complex interactive widgets to components in the target framework, mounting them inside the existing pages. Keep both running during the transition and remove jQuery when nothing depends on it.

    Longer Answer

    Practical steps: measure where jQuery is used (lint rules such as eslint-plugin-no-jquery can flag usage and block new code), write tests around critical behaviour first, start with leaf features, and watch out for plugins (date pickers, sliders) that have no drop-in replacement. A framework and jQuery should not manipulate the same DOM nodes, or the framework will overwrite jQuery's changes (and vice versa).

    For server-rendered apps, lightweight tools such as Alpine.js or htmx can replace much jQuery code with less JavaScript.

    Key Points

    • Stop new jQuery; migrate incrementally.
    • Native APIs for utilities.
    • Framework components for complex widgets.
    • Never share DOM nodes between jQuery and a framework.

    Permalink

  16. Most asked What are the native JavaScript equivalents of common jQuery operations?

    Summary

    $(sel) becomes document.querySelectorAll(sel); .addClass/.removeClass/.toggleClass become el.classList.add/remove/toggle; .on() becomes addEventListener (delegation via event.target.closest(sel)); .closest() is el.closest(); .text() / .html() are textContent / innerHTML; .attr() is getAttribute/setAttribute; .data() is el.dataset; $.ajax is fetch; and $(fn) is DOMContentLoaded or a defer script.

    Longer Answer

    document.querySelector("#orders").addEventListener("click", (e) => {
      const btn = e.target.closest(".delete-order");
      if (!btn) return;
      e.preventDefault();
      deleteOrder(btn.dataset.id);
    });
    

    Differences to remember: querySelectorAll returns a static NodeList (use forEach or spread it), native methods do not apply to a whole collection automatically, and fetch does not reject on HTTP errors, so check response.ok.

    Key Points

    • querySelectorAll, classList, closest, dataset.
    • addEventListener + closest for delegation.
    • fetch instead of $.ajax.
    • Collections and fetch errors behave differently.

    Permalink

  17. Most asked A jQuery click handler fires two or three times per click. What is the likely cause, and how do you fix it?

    Summary

    The handler was bound more than once: typically inside a function that runs on every AJAX refresh or page update, or on elements that were re-rendered while old handlers stayed attached to a parent. Each binding adds another handler.

    Longer Answer

    Fixes: bind once with event delegation on a stable container, outside the refresh function; if a handler must be re-bound, remove it first with a namespace (.off("click.cart").on("click.cart", ...)); use .one() for genuinely single-use handlers. Debug by inspecting the element's listeners in browser DevTools (Event Listeners panel) or $._data(element, "events") in older versions.

    Key Points

    • Handlers bound repeatedly.
    • Delegate once on a stable container.
    • Namespaced .off before .on.
    • Inspect listeners in DevTools.

    Deep dive: Code Clinic: review a jQuery shopping cart script

    Permalink

  18. Most asked Can jQuery be used together with React or Vue?

    Summary

    Yes, but carefully: the framework assumes it owns its DOM, so jQuery must not modify elements the framework renders, or the framework will overwrite the changes or crash during updates. The safe pattern is to give a jQuery plugin a container element the framework never touches, initialise it after mount, and destroy it before unmount.

    Longer Answer

    In React, use a ref, initialise the plugin in useEffect, and return a cleanup that calls the plugin's destroy method; render nothing inside the container. In Vue, use a template ref with onMounted and onBeforeUnmount. Communicate through callbacks and props, not by reading the DOM. This is a transition strategy for legacy widgets, not a long-term architecture.

    Key Points

    • Frameworks own their DOM.
    • Give jQuery an isolated container.
    • Init after mount; destroy before unmount.
    • Transitional, not long term.

    Permalink

  19. How do jQuery selectors perform, and how do you write efficient ones?
  20. Explain DOM traversal methods such as find, closest, parent, parents, children and siblings.
  21. How do you build and insert many elements efficiently and safely with jQuery?
  22. How does .data() work, and how does it relate to data-* attributes?
  23. How do you send a CSRF token with every jQuery AJAX request?
  24. Why should you never use async: false in $.ajax?
  25. How do you write a jQuery plugin?
  26. What is `this` inside a jQuery event handler, and what changes with arrow functions?
  27. How do cross-origin requests work with jQuery? Explain JSONP and CORS.
  28. Why debounce or throttle scroll and resize handlers, and how?
  29. What are namespaced events, and why use them?
  30. How do jQuery Deferreds differ from native Promises, and what changed in jQuery 3?
  31. jQuery animations or CSS transitions: which should you use?
  32. How does method chaining work in jQuery, and what does .end() do?
  33. What is the difference between $.each(), .each() and .map()?
  34. What does jQuery.noConflict() do?
  35. How do .trigger() and .triggerHandler() differ, and how do you use custom events?
  36. How do you serialize and submit a form with jQuery?
  37. How do you handle AJAX errors globally in jQuery?
  38. What is the difference between this and $(this)?
  39. What does the $() function actually return?
  40. What accessibility problems are common in jQuery-built widgets?
  41. How do you test code that uses jQuery?
  42. How does jQuery's .load() method work, and what is the security concern?