jQuery Interview Questions and Answers
Practice jQuery interview questions and answers organized by difficulty, with revealable explanations and related topics.
Entry questions
1 questions- Question 1Entry
What is jQuery?
- jQuery
Reveal answerHide answer
jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.
Mid questions
16 questions- Question 1Mid
How to create clone of any object using jQuery?
- jQuery
Reveal answerHide answer
jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
$(document).ready(function(){ $('#btnClone').click(function(){ $('#dvText').clone().appendTo('body'); return false; }); }); The default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well. $(document).ready(function(){ $("#btnClone").bind('click', function(){ $('#dvClickme').clone(true).appendTo('body'); }); - Question 2Mid
When would you use AngularJS vs jQuery?
- jQuery
Reveal answerHide answer
jQuery - is a library used for DOM Manipulations - Has nothing to do with models - don't have two-way binding feature - becomes complex and difficult to maintain when size of project increases - Sometimes you have to write more code to achieve the same functionality as in Angular Angular - is a MVVM Framework - Used for creating SPA (Single Page Applications) - Has key features like routing, directives, two way data binding, models, dependency injection, unit tests etc - is modular - Maintainable, when project size increases - is Fast and many more. Basically jQuery is a single tool (solves one specific problem: dom manipulation) where AngularJS is a whole toolbox with all kind of tools for different problems (routing, modelbindings, dom manipulation, etc.). Actually jqLite (subset of jQuery) is part of the AngularJS and you use it to solve the dom-manipulation thing.
- Question 3Mid
What are various methods to make ajax request in jQuery?
- jQuery
Reveal answerHide answer
Using below jQuery methods, you can make ajax calls.
load() : Load a piece of html into a container DOM $.getJSON() : Load JSON with GET method. $.getScript() : Load a JavaScript file. $.get() : Use to make a GET call and play extensively with the response. $.post() : Use to make a POST call and don't want to load the response to some container DOM. $.ajax() : Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly. - Question 4Mid
What is chaining in jQuery?
- jQuery
Reveal answerHide answer
Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on. Consider:
$(document).ready(function(){ $('#dvContent').addClass('dummy') .css('color', 'red') .fadeIn('slow'); }); - Question 5Mid
What is the difference between event.PreventDefault() and event.stopPropagation() ?
- jQuery
Reveal answerHide answer
event.preventDefault() : Stops the default action of an element from happening. event.stopPropagation() : Prevents the event from bubbling up the DOM tree, preventing any parent handlersfrom being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.
- Question 6Mid
What is difference between prop and attr ?
- jQuery
Reveal answerHide answer
attr() : Get the value of an attribute for the first element in the set of matched elements. Whereas, .prop() : (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements. Attributes carry additional information about an HTML element and come in name="value" pairs. Where Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties.
attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state. Find out more here.
- Question 7Mid
Is there any difference between body.onload() and document.ready() function?
- jQuery
Reveal answerHide answer
document.ready() function is different from body onload() function for several reasons: 1. We can have more than one document.ready() function in a page where we can have only one body onload function. 2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called wheneverything gets loaded on the page that includes DOM, images and all associated resources of the page.
- Question 8Mid
What is wrong with this code line $('#myid\\.3').text('blah blah!!!');
- jQuery
Reveal answerHide answer
The problem with above statement is that the selectors is having meta characters and to use any of the meta-
characters ( such as !"#("#foo\.bar").So the correct syntax is:
$('#myid\\\\.3').text('blah blah!!!'); - Question 9Mid
What is the difference between eq() and get() methods in jQuery?
- jQuery
Reveal answerHide answer
eq() returns the element as a jQuery object. This method constructs a new jQuery object from one elementwithin that set and returns it. That means that you can use jQuery functions on it.
get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But asit is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used.
- Question 10Mid
What is the difference between jquery.size() and jquery.length ?
- jQuery
Reveal answerHide answer
jQuery .size() method returns number of element in the object. But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call.
- Question 11Mid
Difference between $(this) and this in jQuery?
- jQuery
Reveal answerHide answer
this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.
$(document).ready(function(){ $('#spnValue').mouseover(function(){ alert($(this).text()); }); }); In below example, this is an object but since it is not wrapped in $() , we can't use jQuery method and use thenative JavaScript to get the value of span element.
$(document).ready(function(){ $('#spnValue').mouseover(function(){ alert(this.innerText); }); }); - Question 12Mid
How jQuery selectors are executed?
- jQuery
Reveal answerHide answer
Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class " .myCssClass " and after that it will reject all the other elements which are not in "p#elmID".
$("p#elmID .myCssClass"); - Question 13Mid
What are the fastest/slowest selectors in jQuery?
- jQuery
Reveal answerHide answer
ID and element selectors are the fastest selectors in jQuery. Class selectors are the slow compared to ID and element.
- Question 14Mid
What are selectors in jQuery and how many types of selectors are there?
- jQuery
Reveal answerHide answer
To work with an element on the web page, first we need to find them. To find the html element in jQuery we use selectors. There are many types of selectors but basic selectors are: Name: Selects all elements which match with the given element Name. #ID: Selects a single element which matches with the given ID .Class: Selects all elements which match with the given Class.
Universal (*): Selects all elements available in a DOM.Multiple Elements E, F, G: Selects the combined results of all the specified selectors E, F or G. Attribute Selector: Select elements based on its attribute value.
- Question 19Mid
Which is fast document.getElementByID('txtName') or $('#txtName') ?
- jQuery
Reveal answerHide answer
Native JavaScipt is always fast. jQuery method to select txtName " $('#txtName') " will internally makes a call to
document.getElementByID('txtName') . As jQuery is written on top of JavaScript and it internally uses JavaScriptonly so JavaScript is always fast.
- Question 20Mid
What is the difference between parent() and parents() methods in jQuery?
- jQuery
Reveal answerHide answer
The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.
Senior questions
11 questions- Question 1Senior
What is the difference between event.PreventDefault() and return false ?
- jQuery
Reveal answerHide answer
e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up andreturn false will do both.
- Question 2Senior
How does caching helps and how to use caching in jQuery?
- jQuery
Reveal answerHide answer
Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
$("#myID").css("color", "red"); //Doing some other stuff...... $("#myID").text("Error occurred!");Now in above jQuery code, the element with `#myID` is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be, ```js ```js var $myElement = $("#myID").css("color", "red"); //Doing some other stuff...... $myElement.text("Error occurred!");So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again. ## Q3: What are `deferred` and `promise` object in jQuery? ☆☆☆☆ **Topics:** jQuery ### Answer: * A **deferred object** is an object than can *create* a promise and change its state to `resolved` or `rejected`. Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the **producer** of the value. * A **promise** is, as the name says, a promise about a future value. You can attach callbacks to it to get that value. The promise was "given" to you and you are the **receiver** of the future value. You cannot modify the state of the promise. Only the code that *created* the promise can change its state. ## Q4: How can I get jQuery to perform a _synchronous_, rather than _asynchronous_, Ajax request? ☆☆☆☆ **Topics:** jQuery ### Answer: You specify the asynchronous option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds. Consider: ```js beforecreate: function (node, targetNode, type, to) { ```js jQuery.ajax({ url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), success: function (result) { if (result.isOk == false) alert(result.message); }, async: false }); } - Question 5Senior
Is there any significant difference between event.preventDefault() vs. return false to stop event propagation?
- jQuery
Reveal answerHide answer
return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.
e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the eventfrom bubbling up and return false will do both. Note that this behaviour differs from
normal (non-jQuery)event handlers, in which, notably, return false does not stop the event from bubbling up.
- Question 6Senior
What is the difference between event.stopPropagation and event.stopImmediatePropagation ?
- jQuery
Reveal answerHide answer
event.stopPropagation() allows other handlers on the same element to be executed, while
event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block. $("p").click(function(event){ event.stopImmediatePropagation(); }); $("p").click(function(event){ // This function won't be executed $(this).css("background-color", "#f00"); });If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation() , the next p click event will not fire.
- Question 7Senior
Is it possible to hold or delay document.ready execution for sometime?
- jQuery
Reveal answerHide answer
Yes, its possible. With Release of jQuery 1.6, a new method " jQuery.holdReady(hold) " was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.
$.holdReady(true); $.getScript("myplugin.js", function() { $.holdReady(false); }); - Question 15Senior
Explain .bind() vs .live() vs .delegate() vs .on()
- jQuery
Reveal answerHide answer
All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other. .bind() : This is the easiest and quick method to bind events. But the issue with bind() is that it doesn't work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection. .live() : This method overcomes the disadvantage of bind() . It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method. .delegate() : The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored and it also supports chaining. .on() : Since live was deprecated with 1.7, so new method was introduced named ".on()". This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.
- Question 16Senior
What is the difference between $('div') and $('<div/>') in jQuery?
- jQuery
Reveal answerHide answer
$('<div/\>') : This creates a new div element. However this is not added to DOM tree unless you don'tappend it to any DOM element. $('div') : This selects all the div element present on the page.
- Question 17Senior
How do you attach a event to element which should be executed only once?
- jQuery
Reveal answerHide answer
Using jQuery one() method. This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.
$(document).ready(function() { $("#btnDummy").one("click", function() { alert("This will be displayed only once."); }); }); - Question 18Senior
In what situation you would use multiple version of jQuery and how would you include them?
- jQuery
Reveal answerHide answer
Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page. Below code shows how to include multiple version of jQuery.
<script type='text/javascript'\> var $jq = jQuery.noConflict(); </script\> <script type='text/javascript' src='js/jquery\1.7.2.min.js'\></script\>By this way, for your own jQuery code use " " as " " refers to 1.7.2.
- Question 19Senior
Is there any advantage of using $.ajax() for ajax call against $.get() or $.post() ?
- jQuery
Reveal answerHide answer
By using jQuery post() / jQuery get() , you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response. Where jQuery.ajax() is jQuery's low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks). jq′′, insteadof′′ jq′′referstojQuery1.9.1, where′′
- Question 20Senior
What are the differences between JavaScript's window.onload and jQuery's $(document).ready() method?
- jQuery
Reveal answerHide answer
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded. The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
Expert questions
4 questions- Question 1Expert
Is it possible to hold or delay document.ready execution for sometime?
- jQuery
Reveal answerHide answer
Yes, its possible. With Release of jQuery 1.6, a new method " jQuery.holdReady(hold) " was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.
$.holdReady(true); $.getScript("myplugin.js", function() { $.holdReady(false); }); - Question 8Expert
What is the advantage of using protocol less URL while referencing jQuery from CDNs?
- jQuery
Reveal answerHide answer
It is quite useful when you are moving from HTTP to HTTPS url. You need to make sure that correct protocol is used for referencing jQuery library as pages served via SSL should contain no references to content served through unencrypted connections. "protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead.
- Question 9Expert
Is it possible to get value of multiple CSS properties in single statement?
- jQuery
Reveal answerHide answer
Well, before jQuery 1.9 release it was not possible but one of the new feature of jQuery 1.9 was .css() multi- property getter.
var propCollection = $("#dvBox").css(["width", "height", "backgroundColor"]);In this case, the propCollection will be an array and it will look something like this.
{ width: "100px", height: "200px", backgroundColor: "#FF00FF" } - Question 11Expert
How can I implement my own $(document).ready functionality without using jQuery?
- jQuery
Reveal answerHide answer
There is a standards based replacement, DOMContentLoaded that is supported by over 98% of browsers, though not IE8:
document.addEventListener("DOMContentLoaded", function(event) { //do work });
Junior questions
17 questions- Question 2Junior
What is the difference between .js and .min.js files?
- jQuery
Reveal answerHide answer
jQuery library comes in 2 different versions Development and Production/Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.
- Question 3Junior
What is event.PreventDefault() ?
- jQuery
Reveal answerHide answer
The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.
- Question 4Junior
What is the use of jQuery .each() function?
- jQuery
Reveal answerHide answer
The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.
- Question 5Junior
What does $('div.parent') will select?
- jQuery
Reveal answerHide answer
All the div element with parent class.
- Question 6Junior
How to select element having a particular class ( .selected )?
- jQuery
Reveal answerHide answer
$('.selected') . This selector is known as class selector. We need to prefix the class name with "." (dot).
- Question 7Junior
What does $("div") will select?
- jQuery
Reveal answerHide answer
This will select all the div elements on page.
- Question 8Junior
How do you select element by ID in jQuery?
- jQuery
Reveal answerHide answer
To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select element with ID "txtName", then syntax would be,
$('#txtName') - Question 9Junior
What is a CDN?
- jQuery
Reveal answerHide answer
A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance. There are 3 popular jQuery CDNs:
-
- Google.
-
- Microsoft
-
- jQuery. Advantages of using CDN: It reduces the load from your server. It saves bandwidth. jQuery framework will load faster from these CDN. The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN
- Question 10Junior
What is jQuery.noConflict ?
- jQuery
Reveal answerHide answer
As other client side libraries like MooTools, Prototype can be used with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict() .
jQuery.noConflict(); // Use jQuery via jQuery(...) jQuery(document).ready(function(){ jQuery("div").hide(); });You can also use your own specific character in the place of $ sign in jQuery.
var $j = jQuery.noConflict(); // Use jQuery via jQuery(...) $j(document).ready(function(){ $j("div").hide(); }); - Question 11Junior
Can we have multiple document.ready() function on the same page?
- jQuery
Reveal answerHide answer
YES. We can have any number of document.ready() function on the same page.
- Question 12Junior
What does dollar sign ( $ ) means in jQuery?
- jQuery
Reveal answerHide answer
Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.
$(document).ready(function(){ });Over here $ sign can be replaced with "jQuery" keyword.
jQuery(document).ready(function(){ }); - Question 13Junior
Which is the starting point of code execution in jQuery?
- jQuery
Reveal answerHide answer
The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.
- Question 14Junior
Is jQuery a W3C standard?
- jQuery
Reveal answerHide answer
No. jQuery is not a W3C standard.
- Question 15Junior
Is jQuery a library for client scripting or server scripting?
- jQuery
Reveal answerHide answer
Client side scripting.
- Question 16Junior
Is jQuery replacement of JavaScript?
- jQuery
Reveal answerHide answer
No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.
- Question 17Junior
How JavaScript and jQuery are different?
- jQuery
Reveal answerHide answer
JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.
- Question 18Junior
Why do we use jQuery?
- jQuery
Reveal answerHide answer
Due to following advantages.
Easy to use and learn. Easily expandable. Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+) Easy to use for DOM manipulation and traversal. Large pool of built in methods. AJAX Capabilities. Methods for changing or applying CSS, creating animations. Event detection and handling. Tons of plug-ins for all kind of needs.