Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 56 ยท Practice and Review

jQuery Interview Questions

Thirty common jQuery interview questions with short answers and code: .attr vs .prop, delegation, ready vs load, chaining, noConflict, deferreds and migration.

jQuery questions still turn up in interviews, because so many production sites run on it: WordPress themes, Bootstrap 4 pages, internal admin tools, and applications that are five or ten years old and still earning money. An interviewer rarely wants you to recite the API. They want to know whether you understand what happens underneath, whether you can tell jQuery from plain JavaScript, and whether you know where the library is dangerous or outdated.

This page collects thirty questions in six groups. Each answer is short enough to say aloud in under a minute and, where it helps, comes with a few lines of code. Three live examples let you check the trickiest answers yourself. If an answer feels unfamiliar, follow the link to the lesson that covers it in depth.

What interviewers listen for

Understanding Why it works, not only how to call it.
Trade-offs When jQuery helps and when vanilla JS is better.
Safety XSS, memory leaks and deprecated APIs.
Clarity A short answer with one example beats a long lecture.
1 / 2

The basics

1. What is jQuery and why is it still used?

jQuery is a small JavaScript library that wraps the DOM, events, animations and AJAX in one concise, consistent API. It was created to hide browser differences and to make common tasks short. Today browsers are standardized and the native API is much better, but jQuery remains in a huge number of existing sites and in plugins (including Bootstrap 4 and many WordPress themes), so you will meet it in maintenance work. See what jQuery is and when to use it.

2. What is the difference between $ and jQuery?

None: $ is an alias for the jQuery function. Other libraries also use $, so jQuery offers $.noConflict() to give the name back. Inside a plugin it is common to write (function ($) { ... })(jQuery); so the code can use $ safely.

3. What does $("selector") return?

A jQuery object: an array-like wrapper around zero or more DOM elements, with a length, numeric indexes and all the jQuery methods. It never returns null; when nothing matches it returns an empty collection, and methods called on it do nothing. That is why if ($("#x")) is always true and if ($("#x").length) is the correct existence check. See the jQuery object.

4. How do you get the raw DOM element from a jQuery object, and back?

Use an index or .get(): $("#box")[0] or $("#box").get(0). To go back, wrap the node: $(node). Native properties such as .checked or .classList exist only on the raw element.

5. What is the difference between $(document).ready(), $(window).on("load") and DOMContentLoaded?

ready (and its shorthand $(function () {...})) fires when the DOM has been parsed, which is the same moment as DOMContentLoaded. It does not wait for images, stylesheets or iframes. The load event fires later, after all of those finished. Use ready for attaching handlers and load only when you need image sizes. Since jQuery 3, ready callbacks always run asynchronously, even if the DOM is already ready (see the live example below). More in the document ready lesson.

6. What is chaining and how does it work?

Most jQuery methods return the jQuery object they were called on, so another method can follow immediately: $("#box").addClass("on").fadeIn(200).text("Hi"). Getters are the exception: .text() with no argument returns a string, so it ends the chain. Chaining avoids repeated selections and reads like a sentence, but a very long chain is hard to debug; break it into lines.

7. What is implicit iteration?

Setter methods apply to every element in the collection, and getters read from the first one. $("li").addClass("x") adds the class to all list items without a loop. When you need element-specific logic, use .each() or a function argument such as .text(function (i, old) {...}).

Selecting and traversing

8. How are selectors evaluated, and which ones are slow?

jQuery's selector engine hands standard CSS selectors to the browser's querySelectorAll, which is fast. Extensions that are not CSS, such as :visible, :first, :eq() or :contains(), force jQuery to do the work in JavaScript. Prefer a CSS selector followed by a method: $("li").first() instead of $("li:first"). Selecting by id is the fastest, and caching a selection in a variable avoids repeating the work. See selector performance.

9. What is the difference between .find(), .children() and .filter()?

.find(selector) searches all descendants at any depth. .children() looks only at the direct children. .filter(selector) does not move through the tree at all; it keeps the members of the current collection that match. .closest() goes the other way, up through the ancestors.

10. What is the difference between .attr() and .prop()?

Attributes are what the HTML says; properties are the live state of the DOM object. For checked, selected, disabled and value, the property changes when the user interacts, while the attribute keeps the initial value. Use .prop() for state and .attr() for real attributes such as href, aria-* and data-*. The example below shows the difference.

Attribute versus property

See attributes and properties.

11. What are the differences between .text(), .html() and .val()?

.text() gets or sets text content and escapes markup, so it is safe for untrusted data. .html() gets or sets markup and parses it, which can run injected scripts or event attributes if the string contains user input. .val() reads or writes the value of form controls. See getting and setting content.

12. How does .data() differ from data-* attributes?

.data("key") reads the matching data-key attribute once, converts it ("5" becomes the number 5, "true" becomes true, JSON text becomes an object) and caches it. Later changes with .data("key", value) live in jQuery's cache and are not written back to the attribute, and the attribute is not re-read. Use .attr("data-key") if you need the current attribute string. See storing data with .data().

13. What is the difference between .remove(), .detach() and .empty()?

.remove() takes the elements out of the DOM and also deletes their jQuery data and event handlers. .detach() takes them out but keeps data and handlers, so you can put them back later. .empty() removes the children and leaves the element itself. Using .remove() on elements that were wired with jQuery is how you avoid memory leaks. See removing and replacing.

14. What does .clone(true) do?

.clone() copies elements and their children. Passing true also copies the jQuery data and the event handlers attached to the original. Remember that copying an element with an id creates duplicate ids unless you change them.

15. What is the difference between .append() and .appendTo()?

They do the same insertion with the operands swapped. $("ul").append(li) returns the ul collection, while $(li).appendTo("ul") returns the inserted li. Choose the one that leaves the right object in your chain. Inserting an element that is already in the page moves it. See inserting content.

Events

16. How do .on(), .click(), .bind(), .live() and .delegate() relate?

.on() is the single, modern way to attach handlers, with or without delegation. .click(fn) is a shorthand for .on("click", fn), and .click() with no argument triggers the event. .bind() and .delegate() were the older forms and have been deprecated since jQuery 3.0; .live() was removed in 1.9. Use .on() and .off() only. See handling events.

17. What is event delegation and why use it?

Events bubble up the tree, so one handler on a parent can serve all matching descendants, present and future: $("#list").on("click", "li", fn). It uses less memory than one handler per child, it works for elements created later, and it simplifies cleanup. Be aware that events which do not bubble need special handling (use focusin and focusout instead of focus and blur). See event delegation.

18. What are this, event.target and event.currentTarget?

In a delegated handler, this and event.currentTarget are the element that matched the selector, and event.target is the deepest element that was actually clicked, which may be a child. In a non-delegated handler this is the element the handler was bound to. Run the example to see the three side by side.

this versus event.target

19. What do preventDefault(), stopPropagation() and return false do?

event.preventDefault() cancels the browser's default action (following a link, submitting a form). event.stopPropagation() stops the event from bubbling to ancestors. Returning false from a jQuery handler does both. Avoid return false unless you want both effects, because stopping propagation breaks delegated handlers further up and analytics code. event.stopImmediatePropagation() also prevents other handlers on the same element. See the event object.

20. How do you remove handlers, and what are event namespaces?

.off("click") removes click handlers; .off("click", handler) removes one. Namespaces label handlers: .on("click.menu", fn) can be removed with .off(".menu") without touching handlers added by someone else. .one() attaches a handler that runs at most once.

21. What is the difference between .trigger() and .triggerHandler()?

.trigger() fires the event on every matched element, lets it bubble and also runs the browser's default action where one exists. .triggerHandler() runs only the jQuery handlers of the first matched element, does not bubble, does not perform the default action and returns what the last handler returned.

Effects and animation

22. How do .hide(), .fadeOut() and .slideUp() differ, and why does .stop() matter?

.hide() with no duration is instant; with a duration it animates width, height and opacity together. .fadeOut() animates only opacity and .slideUp() only height. All of them end with display: none. Animations are queued per element, so repeated hovering piles up effects; call .stop(true, true) before starting a new one. See the animation queue.

23. What can .animate() not do?

It animates numeric CSS properties only. Colors need a plugin, and transform is not animatable in a simple way. For simple visual effects, CSS transitions are smoother because the browser runs them off the main thread; use .animate() for scroll positions and for numbers that are not CSS at all.

AJAX and deferreds

24. What is the difference between $.ajax(), $.get() and .load()?

$.ajax() is the full-featured function with a settings object. $.get(), $.post() and $.getJSON() are shorthands that call it with preset options. .load(url) fetches HTML and puts it into the matched elements, optionally only a fragment. The dataType option tells jQuery how to parse the response; without it jQuery guesses from the Content-Type header. See AJAX with $.ajax().

25. What is a Deferred, and what is special about jQuery 3?

A Deferred is an object that represents work finishing later; its .promise() is the read-only view. AJAX calls return such an object (jqXHR). You attach .done(), .fail(), .always(), and chain with .then(). Since jQuery 3 the .then() method is Promises/A+ compatible: callbacks run asynchronously and an exception in one rejects the next promise instead of escaping. .done() and .fail() still run synchronously. $.when(a, b) waits for several promises. The example shows the ordering.

done is synchronous, then is not

See Deferreds, promises and Ajax events.

26. How do you handle cross-domain requests?

The browser's same-origin policy blocks them unless the server sends CORS headers (Access-Control-Allow-Origin), in which case a normal $.ajax() works. The old workaround is JSONP (dataType: "jsonp"), which injects a script tag; it is limited to GET and gives the other site full script access, so avoid it unless there is no alternative. See real-world AJAX patterns.

Advanced topics

27. What does $.noConflict() do?

It gives the $ name back to whichever library had it before jQuery loaded, for example Prototype. You can then use jQuery(...) or save a new alias: var jq = $.noConflict();. $.noConflict(true) also restores the previous jQuery global, which allows two versions to live on one page. See using plugins and jQuery UI.

28. How do you write a jQuery plugin?

Add a function to $.fn, return this.each(...) (or this) to keep the chain, merge defaults with user options through $.extend, and keep per-element state in .data(). Wrap everything in (function ($) { ... })(jQuery);. Namespace events so the plugin can clean up after itself. See writing your own plugin.

JavaScript
(function ($) {
  $.fn.highlight = function (color) {
    return this.css("background", color || "yellow");
  };
})(jQuery);

29. What changed in jQuery 3, and how do you upgrade a legacy site?

jQuery 3 removed or deprecated .size(), .bind(), .delegate(), $.parseJSON(), the .load(), .unload() and .error() event shorthands and several $.is* helpers, made ready asynchronous and .then() standards compliant, and changed details of :visible and .data(). The recommended path is to load the jQuery Migrate plugin, which logs warnings for deprecated calls, fix those, and then remove Migrate. See what changed in jQuery 3.

30. When should you not use jQuery?

On new projects that need only a few DOM helpers, native methods (querySelectorAll, classList, fetch, addEventListener) do the job without 30 KB of extra code. Component frameworks such as React or Vue also manage the DOM themselves, so mixing jQuery in causes conflicts. Keep jQuery when a codebase or a plugin depends on it, or when the cost of rewriting is higher than the benefit. The slim build drops AJAX and effects when you do not use them. See from jQuery to modern JavaScript.

Tips for the interview itself

  • Answer the "why". For "what is delegation", add the reason (dynamic elements, fewer handlers) and one pitfall.
  • Say what is deprecated. Naming .live(), .size() and $.trim() as outdated shows that your knowledge is current.
  • Mention security. Any question about .html(), $() with user strings or JSONP is a chance to talk about XSS.
  • Be honest about vanilla JS. Most interviewers prefer "I would use native code here, but jQuery is fine in this legacy codebase" over defending the library at all costs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the correct way to check whether $("#panel") matched anything?

    jQuery always returns an object, even when nothing matches, so the object is always truthy. Its length is 0 when the selection is empty.
  2. 2. A checkbox starts checked in the HTML and the user unchecks it. What do .attr("checked") and .prop("checked") return?

    The attribute keeps the initial value, so .attr("checked") still returns "checked". The property is the live state, so .prop("checked") is false.
  3. 3. Which statement about jQuery 3 deferreds is true?

    From jQuery 3 .then() follows Promises/A+: asynchronous callbacks and rejections for thrown errors. .done() and .fail() keep their synchronous behavior.
  4. 4. Why is $("#list").on("click", "li", fn) preferable to $("#list li").on("click", fn) for a list that changes?

    The delegated form puts one handler on the stable parent and matches the target at event time, so new items work without rebinding.
  5. 5. What does return false inside a jQuery event handler do?

    In jQuery handlers, return false is shorthand for event.preventDefault() plus event.stopPropagation().

Summary

  • Know the vocabulary: the jQuery object is an array-like wrapper, $ is an alias, chaining works because methods return the collection.
  • Be able to explain ready versus load, .attr() versus .prop(), .remove() versus .detach() and this versus event.target.
  • Prefer .on() with delegation, namespaces and .off(); know that .bind(), .delegate() and .live() are outdated.
  • Explain deferreds: done, fail, always, then, $.when, and the jQuery 3 asynchronous .then().
  • Know how to write a plugin, how noConflict works and how to migrate with jQuery Migrate.
  • Show good judgment: security with .html(), performance with caching and when native JavaScript is the better tool.

Finish the course with the one-page jQuery Cheat Sheet.