jQuery Interview Questions and Answers: Prepare for Front-End Interviews

The jQuery interview questions I would ask, with short model answers and code run on jQuery 1.11.0: attr vs prop, detach vs remove, delegation, deep extend, AJAX errors, plugins, and what jQuery 1.9 removed.

Executive Summary: Good jQuery interview questions check if you have used the library on real pages. The ones that sort candidates have a trap: attr() versus prop(), remove() versus detach(), shallow versus deep $.extend, delegated events, and what a plugin must return. I give 24 questions with short answers, and I ran each code claim on jQuery 1.11.0.
jQuery interview questions illustration: paper-cut armchairs face each other across a small table with a laptop showing code, under speech bubbles and a light bulb

The question I get: “I have a front-end interview coming up, and the job mentions jQuery. Which jQuery interview questions will they ask?” My answer is that good interviewers skip “what does .hide() do”. They ask about behaviour you only know if you have debugged it.

I sort jQuery interview questions into six groups: the basics, selecting and traversing, changing the DOM, events, AJAX, and performance with plugins. Each group has the questions that come up most and a model answer in two or three sentences. Wherever I could test a claim, I show the output from jQuery 1.11.0. The jQuery API documentation is the place to check anything you are unsure of.

My position: answer every question in two parts, “what it does” and “when it goes wrong.” Anyone can recite the first part. The second part proves you have used the thing on a real page. The follow-up question is usually about it.

Basic jQuery interview questions

1. What is jQuery, and why do people use it?

jQuery is a JavaScript library that wraps the browser’s DOM, event and AJAX APIs behind one short, chainable interface. People use it for cross-browser consistency more than for short code. It hides the differences between Internet Explorer 6 to 8 and everything else, so the same code behaves the same way everywhere.

2. What is the difference between jQuery 1.x and 2.x?

The API is the same, and this is one of the easy jQuery interview questions. jQuery 2.0 (April 2013) dropped support for Internet Explorer 6, 7 and 8, which makes it smaller and faster. Use 1.x (1.11 now) if you must support those browsers, and 2.x (2.1) if you do not. Both get the same fixes.

3. What is the difference between $(document).ready() and window.onload?

ready fires once the browser has parsed the DOM, before images and other assets finish downloading. window.onload waits for everything. I prefer ready for attaching behaviour, because the page becomes interactive sooner. Also, onload holds only one handler unless you add your own queue, while ready accepts any number.

4. What does $ mean, and what if another library uses it?

$ is an alias for the global jQuery function. If Prototype or MooTools has taken it, call jQuery.noConflict() to give $ back, and write your code as jQuery(function ($) { … }). That is also why “$ is not defined” shows up on WordPress.

var jq = jQuery.noConflict();
console.log('$ after noConflict:', typeof window.$, '| jq === jQuery:', jq === window.jQuery);
console.log('noConflict(true) also releases jQuery:', typeof jq.noConflict(true));
console.log('window.jQuery now:', typeof window.jQuery);
$ after noConflict: undefined | jq === jQuery: true
noConflict(true) also releases jQuery: function
window.jQuery now: undefined

5. What were .live() and $.browser, and why were they removed?

jQuery 1.9 removed both. .live() bound delegated handlers at the document, which was slow and awkward to stop. .on() replaced it. $.browser guessed the browser from the user-agent string, which breaks whenever a browser changes its string. Feature detection, as in Modernizr, replaced it. This is the state in the current release:

console.log('jQuery', $.fn.jquery);
console.log('$.fn.live  :', typeof $.fn.live, '| $.fn.die:', typeof $.fn.die, '| $.browser:', typeof $.browser);
console.log('$.fn.on    :', typeof $.fn.on, '| $.fn.bind:', typeof $.fn.bind, '| $.fn.delegate:', typeof $.fn.delegate);
jQuery 1.11.0
$.fn.live  : undefined | $.fn.die: undefined | $.browser: undefined
$.fn.on    : function | $.fn.bind: function | $.fn.delegate: function

Selecting and traversing

6. How does jQuery find elements, and why are some selectors slower?

jQuery hands standard CSS selectors to the browser’s native querySelectorAll where it exists, which is fast. jQuery-only selectors such as :first, :eq() and :contains() cannot go that route, so jQuery matches them itself. Put an ID or a class first, then narrow with .find() and .filter().

7. How do you check whether a selector matched anything?

Test .length. This one trips people on jQuery interview questions more than it should. A jQuery object is always truthy, even when empty, so if ($('#x')) is always true. The old .size() method still works and returns length, but jQuery deprecated it in 1.8.

8. What is the difference between .closest() and .parents(), and what does .end() do?

.closest() starts at the element itself and stops at the first matching ancestor. .parents() returns all ancestors. .end() undoes the last filtering step in a chain and returns to the previous set.

console.log('size() still exists :', typeof $.fn.size, '| length:', $('#l li').length);
console.log('index() of .on      :', $('#l li.on').index());
console.log('$.type([])          :', $.type([]), '| $.type(null):', $.type(null), '| typeof null:', typeof null);
console.log('$.isNumeric("12")   :', $.isNumeric('12'), '| "12px":', $.isNumeric('12px'));
console.log('.is(".on")          :', $('#l li').eq(1).is('.on'));
console.log('closest vs parents  :', $('.s').closest('div').attr('id'), '/', $('.s').parents().length, 'ancestors');
console.log('end()               :', $('#l').find('li').filter('.on').end().length, 'li (back to the find set)');
console.log('first, then each text:', $('#l li').map(function () { return $(this).text(); }).get().join(''));
console.log('ready alias         :', typeof $(function () {}).ready, '| $(document).ready === $(fn):', typeof $.fn.ready);
size() still exists : function | length: 3
index() of .on      : 1
$.type([])          : array | $.type(null): null | typeof null: object
$.isNumeric("12")   : true | "12px": false
.is(".on")          : true
closest vs parents  : wrap / 4 ancestors
end()               : 3 li (back to the find set)
first, then each text: abc
ready alias         : function | $(document).ready === $(fn): function

The same run shows two classic gotcha answers. $.type(null) returns "null" while typeof null is "object". And $.isNumeric("12px") is false while $.isNumeric("12") is true.

Changing the DOM and the data

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

An attribute is what the HTML says. A property is the live state of the element. They start equal and then drift apart. For anything that changes at run time, such as checked, disabled, selected or an input’s value, use .prop() (added in 1.6). Use .attr() for things like href or data-* attributes. Of all jQuery interview questions, this is the one I would bet on.

var $c = $('#chk');
console.log('attr("checked") :', $c.attr('checked'));
console.log('prop("checked") :', $c.prop('checked'));
$c.prop('checked', false);
console.log('after unchecking -> attr:', $c.attr('checked'), '| prop:', $c.prop('checked'));
console.log('value attr vs prop:', $('#txt').attr('value'), '/', $('#txt').prop('value'));
$('#txt').val('typed');
console.log('after .val("typed") -> attr:', $('#txt').attr('value'), '| prop/val:', $('#txt').val());
attr("checked") : checked
prop("checked") : true
after unchecking -> attr: checked | prop: false
value attr vs prop: abc / abc
after .val("typed") -> attr: abc | prop/val: typed

After I unchecked the box, the attribute still says checked, because it records the HTML as written. The property says false. Typed values behave the same way: .attr('value') stays on the original text, and .val() reads the live one.

10. What does .data() do, and how is it different from .attr('data-…')?

.data() reads data-* attributes once, converts types (numbers, booleans, JSON), and then keeps its own copy in memory. Writing with .data('x', v) does not update the HTML attribute.

var $p = $('#p1');
console.log('data("userId")    :', $p.data('userId'), typeof $p.data('userId'));
console.log('data("active")    :', $p.data('active'), typeof $p.data('active'));
console.log('data("tags")      :', JSON.stringify($p.data('tags')), Array.isArray($p.data('tags')));
console.log('attr("data-note") :', $p.attr('data-note'));
$p.data('userId', 99);
console.log('after data("userId", 99): data =', $p.data('userId'), '| attr =', $p.attr('data-user-id'));
data("userId")    : 42 number
data("active")    : true boolean
data("tags")      : ["x","y"] true
attr("data-note") : hello
after data("userId", 99): data = 99 | attr = 42

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

.remove() takes the elements out and discards their data and event handlers. .detach() takes them out but keeps the data and handlers, so you can put them back later. That makes it the right tool for a heavy edit done off the page. .empty() removes the element’s children and leaves the element itself.

$('#l li.on').click(function () {}).data('k', 'kept?');
var li = $('#l li.on');
var detached = li.detach();
console.log('detach -> data kept:', detached.data('k'), '| events kept:', !!$._data(detached[0], 'events'));
$('#l').append(detached);
var removed = $('#l li.on').remove();
console.log('remove -> data kept:', removed.data('k'), '| events kept:', !!$._data(removed[0], 'events'));
$('#l').empty();
console.log('empty -> children left:', $('#l').children().length);
detach -> data kept: kept? | events kept: true
remove -> data kept: undefined | events kept: false
empty -> children left: 0

12. What is the difference between .html(), .text() and .append()?

.html() replaces the contents with parsed markup. .text() replaces them with escaped text, the safe choice for user input. .append() adds to the end and leaves existing children alone.

13. What is the difference between .clone() and .clone(true), and between shallow and deep $.extend?

.clone() copies the elements only. .clone(true) also copies their event handlers and data. Deep versus shallow $.extend is one of the harder jQuery interview questions. $.extend(a, b) merges only the top level, so a nested object in b replaces the one in a entirely. $.extend(true, a, b) merges recursively.

var defaults = { color: 'red', size: { w: 1, h: 2 } };
var shallow = $.extend({}, defaults, { size: { w: 9 } });
var deep = $.extend(true, {}, defaults, { size: { w: 9 } });
console.log('shallow:', JSON.stringify(shallow.size), '(h is gone)');
console.log('deep   :', JSON.stringify(deep.size));

$('#l li:first').on('click', function () {});
console.log('clone()     keeps events:', !!$._data($('#l li:first').clone()[0], 'events'));
console.log('clone(true) keeps events:', !!$._data($('#l li:first').clone(true)[0], 'events'));
shallow: {"w":9} (h is gone)
deep   : {"w":9,"h":2}
clone()     keeps events: false
clone(true) keeps events: true

The shallow merge lost h, because it replaced the whole size object. The deep merge kept it. Pass an empty object first, as in $.extend({}, defaults, options), so you do not change your defaults.

14. What do .width(), .innerWidth() and .outerWidth() return?

The content width, content plus padding, and content plus padding plus border. Passing true to .outerWidth() adds the margin. Unlike .css('width'), they return numbers, not strings like "200px".

var $w = $('#w');
console.log('css("width")        :', JSON.stringify($w.css('width')));
console.log('width()             :', $w.width(), typeof $w.width());
console.log('innerWidth()        :', $w.innerWidth());
console.log('outerWidth()        :', $w.outerWidth());
console.log('outerWidth(true)    :', $w.outerWidth(true));
css("width")        : "200px"
width()             : 200 number
innerWidth()        : 220
outerWidth()        : 224
outerWidth(true)    : 224

15. What do .serialize(), .serializeArray() and $.param() do?

.serialize() turns a form’s fields into a URL-encoded string for sending. .serializeArray() returns an array of {name, value} objects, and $.param() encodes any object the same way. Fields without a name, disabled fields and unchecked boxes are skipped.

console.log('serialize()      :', $('#f').serialize());
console.log('serializeArray() :', JSON.stringify($('#f').serializeArray()));
console.log('$.param          :', $.param({ q: 'a b', tags: ['x', 'y'], n: { k: 1 } }));
serialize()      : q=jquery+tips&page=2&s=1
serializeArray() : [{"name":"q","value":"jquery tips"},{"name":"page","value":"2"},{"name":"s","value":"1"}]
$.param          : q=a+b&tags%5B%5D=x&tags%5B%5D=y&n%5Bk%5D=1

jQuery interview questions on events

16. What is event delegation, and why use it?

Events bubble up the tree. So one handler on a parent can handle events from its children, even ones added later: $('#list').on('click', 'li', fn). It saves memory, with one handler instead of one per row, and it survives content replacement. Among jQuery interview questions on events, this one comes up first. I show the missed-element bug in my post on jQuery event handling.

17. What is the difference between preventDefault(), stopPropagation() and return false?

Expect this among jQuery interview questions on events. The first cancels the browser’s default action, and the second stops bubbling. return false in a jQuery handler does both. I prefer the explicit calls, because return false can quietly block other handlers up the tree.

18. What is the difference between this and e.target?

In a delegated handler, this is the element that matched your selector, and e.target is the deepest element actually clicked, which may be a child of it. Wrap with $(this) to use jQuery methods.

jQuery interview questions on AJAX

19. How does jQuery AJAX report errors, and what are the textStatus values?

Through .fail() or the error option. textStatus is error for an HTTP error, timeout, abort, or parsererror when the body cannot be parsed even though the status was 200. A status of 0 means no response arrived at all.

20. How do you make a cross-domain request?

The browser’s same-origin policy blocks it by default. One option is JSONP (dataType: 'jsonp'), which works for GET only and needs server support. Another is CORS, where the server sends an Access-Control-Allow-Origin header. It works in current browsers and Internet Explorer 10, but not 8 or 9. The last option is a proxy on your own server. Be ready to say JSONP is a security trade-off, because it runs the other site’s code in your page.

21. What is a Deferred, and what does $.when() do?

A Deferred stands for an operation that completes later, with done, fail and always callbacks. $.when(a, b) returns a promise that resolves when all the inputs resolve, and rejects as soon as one fails. My jQuery Deferred post covers how exceptions differ from standard promises.

Performance and plugins

22. How do you make jQuery code faster?

Cache selections in variables. Start from an ID and use .find(). Delegate events instead of binding many. Build markup as one string and insert it once, rather than inside a loop that touches the page on every pass. Avoid changing layout in a loop.

23. How do you write a jQuery plugin?

Plugin jQuery interview questions often end with a whiteboard. Add a function to $.fn, merge options with $.extend over defaults, and return this.each(…). That way the plugin works on every matched element and stays chainable. Wrap it in an IIFE that takes $, so it still works when $ belongs to another library. The plugin guide on learn.jquery.com walks through the pattern.

// A minimal, chainable plugin with overridable defaults
(function ($) {
  $.fn.highlight = function (options) {
    var settings = $.extend({ color: 'yellow', className: 'hl' }, options);
    return this.each(function () {
      $(this).css('background-color', settings.color).addClass(settings.className);
    });
  };
})(jQuery);

var $items = $('#l li');
var result = $items.highlight({ color: 'orange' }).addClass('chained');
console.log('returns the same set (chainable):', result.length === $items.length);
console.log('background of first item        :', $items.first().css('background-color'));
console.log('classes on first item           :', $items.first().attr('class'));
returns the same set (chainable): true
background of first item        : rgb(255, 165, 0)
classes on first item           : hl chained

24. When would you not use jQuery?

I skip it for a small feature on a page that does not otherwise need the library. jQuery 1.11.0 is about 96KB minified (I measured 96,416 bytes, or 33,247 bytes gzipped). I also skip it where only current browsers matter and native methods such as querySelectorAll and classList will do. Large applications are better off with a structured framework. A good answer shows you know the native versions, which I collect in my post on vanilla JavaScript equivalents.

Traps interviewers probe

Topic The trap The correct answer
Empty selection if ($('#x')) Always true; test .length
Checkbox state .attr('checked') after unchecking Use .prop('checked')
Dynamic content Direct handler on a replaced element Delegate from a stable parent
Config merge Shallow $.extend with nested objects Pass true for a deep merge
Loop control Bare return to break from .each() return false
Removing elements .remove() then re-inserting Use .detach() to keep handlers
Upgrades Using .live() or $.browser Removed in 1.9; use .on() and feature detection

How teams run jQuery interviews

  • A small live task on a broken page. The candidate gets a page where a handler stops firing after an AJAX update and has to find out why. The cause is almost always delegation or loading order.
  • Follow-up on “why”, not “what”. Interviewers pick one answer (“you said prop“) and ask what the failure looks like with the wrong one.
  • Debugging in the browser console. Candidates who check typeof jQuery, $.fn.jquery and the Network tab first sound like people who have fixed real pages.
  • Code review of a plugin. Reviewers look for chainability, namespaced events, defaults merged without changing them, and a way to destroy it.

When I run jQuery interview questions past a candidate, the weak answers sound like the API docs read aloud. The strong ones start the same way and then add a bug: “I used .attr('checked') once and the box state never updated.” That one sentence tells me more than a perfect definition. If you have a story like that for three or four of these topics, you are ready.

How to prepare for jQuery interview questions in a week

  1. Day 1-2: run the examples. Type each code block above into a console on a test page. Output you have seen sticks better than text you have read.
  2. Day 3: events and delegation. Be able to explain bubbling on a whiteboard and write a delegated handler from memory.
  3. Day 4: AJAX failures. List the five ways a request fails and what each looks like.
  4. Day 5: write a plugin. Chainable, with defaults and a namespaced event.
  5. Day 6-7: the native equivalents. For each jQuery call you use, know the plain JavaScript version.

When not to answer with jQuery

  • When asked about JavaScript itself. Closures, this, prototypes and hoisting are language questions. Do not answer them with library calls.
  • When the role is framework-based. If the job is an Angular or Backbone application, show where jQuery fits and where it should keep its hands off the DOM.
  • When you do not know. Say how you would find out: docs, console, a test page. That beats a confident guess.

Common mistakes in interviews

  • Reciting definitions with no failure case. Add “and it goes wrong when…”.
  • Confusing .attr() and .prop(). I see this miss more than any other.
  • Not knowing what changed in 1.9. .live(), $.browser and the two-function .toggle() are fair game.
  • Treating jQuery as the whole of front-end. Interviewers want to see JavaScript underneath.
  • Memorising instead of running. A follow-up question exposes it quickly.
  • Overstating performance claims. Say “measure it” rather than inventing numbers.

FAQ

What are the most common jQuery interview questions?

The most common jQuery interview questions cover .attr() versus .prop(), event delegation, .remove() versus .detach(), AJAX errors, $(document).ready versus window.onload, writing a plugin, and what changed in jQuery 1.9. The follow-up is usually what goes wrong when you pick the wrong option.

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

.attr() reads and writes the HTML attribute as written in the markup. .prop() reads and writes the live property of the element. For state that changes at run time, such as checked or disabled, use .prop(), because the attribute keeps its original value.

What is the difference between jQuery 1.x and 2.x?

The API is the same, but jQuery 2.x drops support for Internet Explorer 6, 7 and 8, which makes it smaller and faster. Choose 1.x if you must support those browsers and 2.x if you do not.

What is event delegation in jQuery?

It means attaching a handler to a parent element and letting events from its children bubble up to it, with $(parent).on('click', '.child', fn). It handles elements added later and keeps one handler in memory instead of one per element.

How do I prepare for a jQuery interview?

Prepare for jQuery interview questions at a keyboard. Run every example in a browser console instead of memorising definitions. Practise explaining delegation and AJAX failure cases out loud. Write a small chainable plugin. Then learn the plain JavaScript version of the jQuery methods you use most.

Interview answers land when they include the failure case, because that is where real experience shows. My rule of thumb for jQuery interview questions: for every method you can name, know what it does, when it goes wrong, and what the plain JavaScript version looks like.

Originally posted on 11 February 2014 and post last modified on 2 November 2026

Front-End Development Interview Questions JavaScript jQuery

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *