JQuery Interview Questions

Don't sweat your next job interview - get all the answers to the toughest jquery interview questions right here! Ace you next jquery interview and land your dream job.

  • 4.5 Rating
  • 30 Question(s)
  • 20 Mins of Read
  • 6533 Reader(s)

Advanced

As of Jquery 1.5, Jquery ajax() returns jqXHR object which implements the Promise interface, the promise includes a callback method called jqXHR.fail();

Ex:

let jqxhr = $.ajax("ServerPage.php")
 .done(function() {
alert( "success" );
 })
  .fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
 });

Question Continued:

$.each(myArray, function( i, item ) {
let item = "<li>" + item + "</li>";
$("#list").append(item);
});

Answer:

The main problem here is that calling append() in a loop is costly and slow.

To optimize it, append them all at once rather than one at a time in the loop as shown below.

let listHtml = "";
$.each(myArray, function(i, item) {
listHtml += "<li>" + item + "</li>";
});
$("#list").html(listHtml);

In the above code, the list of all list items html is prepared within each loop and then updates the html at the end.

Jquery.ajax() method contains a setting called “cache”, by default it takes true and false for ‘script’ and ‘jsonp’. If set it to false, it will force request not to be cached by the browser. It works by appending timestamp to the parameters.

The following is the syntax:

$.ajax({
url: "test.html",
cache: false
})
.done(function( html ) {
  $( "#results" ).append( html );
});  

The above code always loads test.html from the server but never gets loaded from the browser cache.

jQuery provides a way to filter selections based on certain characteristics like even or add.

To find every even row of a table, the selector looks like this:

$('tr:even')

Let’s say If the table has id 'users' then you can do like this:

$('#users tr:even')

Similarly :odd selects every odd row.

$('#users tr:odd’)

jQuery’s hover() function works just like any other event, except that instead of taking one function as an argument, it accepts two functions.

The first function runs when the mouse travels over the element and the second function runs when the mouse moves off the element.

The basic structure looks like this:

$('#element').hover(function1, function2);

For example, when mouses over a link with an ID of menu, you want a submenu with an ID of submenu to appear.

Moving the mouse off of the link hides the submenu again. The following jQuery code will do the trick.

$('#menu').hover(function() {
  $('#submenu').show();
}, function() {
  $('#submenu').hide();
});

To select 2nd element from ul element, you can use nth-child() function and it looks like this:

$('ul > li:nth-child(2)');

To find nth element from the list then you can pass the index 'n' to it.

$('ul > li:nth-child(n)');

The following code finds 2nd element from the list and handles a mouseover event.

   let list = $('ul > li:nth-child(2)');
   list.on('mouseover', function(){
      // mouseover handle logic comes here.
   });

filter() is one of the jQuery DOM traversal methods which constructs a new jQuery object from a subset of the matching elements.

The following code is to select all the links in the page whose host name is different than the site host name and then applies css class name “external”

$('a')
 .filter((i, a) =>
a.hostname && a.hostname !== location.hostname
 )
 .addClass('external');

If you have to call several functions that return promises and take an action only when all are completed then $.when can be used. It provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.

The following is the syntax:

jQuery.when(deferreds);

Look at the following example:

ar promises = [
   $.ajax('http://google.com'),
   $.ajax('http://yahoo.com'),
   $.ajax('http://www.nytimes.com')
];
$.when.apply($, promises).then(
   function(result1, result2, result3){
       console.log('All URLs fetched.');
}
);

The arguments passed to the thenCallbacks provide the resolved values for each of the Deferreds and matches the order the Deferreds were passed to jQuery.when().

Yes, The $.grep() method finds the elements of an array which satisfy a filter function. In this case, the original array is not affected.

The following condition filters numbers above 0 and returns [1,2].

$.grep( [ 0, 1, 2 ], function( n, i ) {
 return n > 0;
})

The following returns [0] because invert set as true.

$.grep([ 0, 1, 2 ], function(n, i) {
return n > 0;
}, true);

The most common way to write a for loop to create one array from another, or an array from an object. JQuery makes it even easier with the $.map utility function.

The syntax:

$.map(collection, callback);
The following statement appends 1 to each element in the array and maps the array into [1, 2, 3, 4, 5].
var numbers = $.map(
  [0, 1, 2, 3, 4],
  function(value) {
  return value + 1;
  }

A promise about 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.

If we request a resource from another website, the result of a long calculation either from server or from a JavaScript function, or the response of a REST service, and we perform other tasks while we await the result. When the latter becomes available (the promise is resolved/fulfilled) or the request has failed (the promise is failed/rejected), we act accordingly.

In Jquery, $.ajax, .fadeOut().promise(),  .fadeIn().promise() returns promise objects.

Deffered() method is used if you write your own function and want to provide a promise to the calling code. A deferred object can create a promise and can change its state to resolved or rejected.

The following is the example of how simple Deffered object works.

// Existing object
var obj = {
hello: function( name ) {
  alert( "Hello " + name );
}
 },
 // Create a Deferred
 defer = $.Deferred();
// Set object as a promise
defer.promise( obj );
// Resolve the deferred
defer.resolve( "John" );
// Use the object as a Promise
obj.done(function( name ) {
 obj.hello( name ); // Will alert "Hello John"
}).hello( "Karl" ); // Will alert "Hello Karl"

There are two ways to stop a form

a)     Return false inside function which is been called on form submit.

The sample code:

<script>
  function formSubmit(){
     return false;
  }
</script>
<form onsubmit="return formSubmit();" >

b)     By using event. preventDefault() to stop the default action on the event.

The sample code:

<form>
 <button class='.submit' type="submit">Submit</button>
</form>
$(function(){
   $('.submit').on('submit', function(event){
       event.preventDefault();
});
})

By default, $.ajax() makes all the requests asynchronously. $.ajax() has a configuration parameter called “async” and by default it is true, by setting it to false make the request synchronous request.

When an ajax request made, if you want to handle when the request completes then .always() will come in handy. .always() is a promise callback method added in jQuery 1.6 and it's a replacement for the deprecated .complete() method.

For example, if you want show a loading indicator when a request made and hide the loading indicator when the request complete, in this case, .always() handler can be useful.

The following is the example:

var jqxhr = $.ajax("example.php")
 .done(function() {
alert("success");
 })
 .fail(function() {
   alert("error");
 })
 .always(function() {
   alert("complete");
 })

Yes, there is a selector called “: contains” which selects the elements that contains the specified text.

Here is the syntax:

$(":contains(text)")

Let's consider the following example which contains a set of div elements contains text.

<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>

The following statement filters all the elements contains text "John" and underlines them.

<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>

Beginner

Question Continued:

Ex: In the following example, hide all the child elements with class name “x”

<div id="parent">
 <Label>Paragraphs</label>
 <p class="x">Para-x</p>
 <p class="y">Para-y</p>
 <p class="x">Para-x</p>
</div>

Answer:
.children([selector]) is to get all the children elements of an element and the selector can be to select className of the element. The following statement is to get all the children with class name “x”.

$("#parent").children( ".x" ).hide();

.hasClass(className) determines if the element contains class name. It returns true if the element contains the class name otherwise returns false.

The following statement determines if the element has class name “X”.

$(element).hasClass(“x”);

The code inside window.onload event won't run until the browser finishes loading entire elements includes images, frames, objects etc.. but document ready runs as soon as the HTML document is loaded and DOM is ready.

The basic structure of ready() function looks like this:

$(document).ready(function() {
 //your code goes here
});

The basic structure of window.onload function looks like this:

    window.onload = function() {
// Your code goes here
 };

As of Feb 2019, the latest version is v.3.3.1. There are two ways to include jquery in html page. The first one is to download the compressed version of jquery file from https://jquery.com/download/ and save it in the scripts directory of the project and then include in html page through <script> tag.

The following is the example.

<script src=”/src/scripts/jquery-3.3.1.min.js”</script>
The second option is to use CDN’s host compressed and uncompressed versions of jquery.
The following are some of the popular CDN’s available.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Or
<script>
src=”https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js”
</script>
  1. Jquery core api is thoroughly verified and tested in all the mostly popular browsers hence jquery eliminates most of the browser compatibility issues with client-side scripting.
  2. Jquery provides css3 selectors to find elements
  3. With Jquery, DOM traverse and manipulation takes less code compared to javascript code.
  4. Jquery Ajax() api simplifies the ajax calls and the way response is handled.

jqXHR stands for jQuery XMLHttpRequest.

As of jQuery 1.5, $.ajax() method returns the jqXHR object, which is a superset of the XMLHTTPRequest object.

jqXHR object implements the Promise interface and provides the following methods to handle ajax requests.

jqXHR.done(function( data, textStatus, jqXHR ) {});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

jQuery(":checkbox") is to select all the checkbox elements, as all the checkboxes are of input elements it is good practice prefix it with type of element like $('input:checkbox'). The following is the query to select all the checkboxes in a form.

$('form input:checkbox')

In jQuery, most DOM events have an equivalent jQuery function.

To assign an event to an element, add a period, the event name and a set of parentheses.

Ex:

The following line add a mouseover event to every link on a page.

$('a').mouseover();

The following line add a click event to every with an Id of menu.

$('#menu').click();

$(‘#menu’) is to select menu element with id ‘menu’

$(‘#menu’).mouseover() is to attach mouseover event.

The following is the way to write a anonymous function inside mouseover() to show submenu.

$('#menu').mouseover(function() {
$('#submenu').show(); // shows the submenu with id ‘submenu’
});

.on() method attach an event handler function for one or more events to selected elements.

In the following code, the event handler function is attached to all the <TR> elements in the table with id “#dataTable” on both click and mouseover events.

$('#dataTable tbody tr').on('click mouseover', function() {
 console.log( $(this).text() );
});

It also delegates the events to the elements dynamically added to the page, in this case, the event handler function will be attached to the dynamically added <TR> elements.

Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs.  A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user.

The following statement is to submit the first form without using the submit() function.

$("form:first").trigger("submit");

The .off() method removes event handlers that were attached with .on().

Calling .off() with no arguments removes all handlers attached to the elements.

The following removes all event handlers from all paragraphs:

$('p').off();

The following removes all delegated click handlers from all paragraphs:

$('p').off('click', '**');

The following removes just one previously bound handler by passing it as the third argument:

$('body').off('click', 'p', foo); // ... Foo will no longer be called.

As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Consider a DOM element defined by the HTML markup

<input type="checkbox" checked="checked" />
$('#check').prop('checked') returns the checked property of the element which is true
$('#check').attr('checked') returns the checked attribute which is "checked".

jQuery .each() method is to iterate over the elements in a jQuery collection without the need for the for loop syntax.

For arrays, array-like objects, and objects, jQuery provides a function named $.each().

The syntax looks like:

$.each(anArray, someComplexFunction);
The following is the example:
let anObject = {one:1, two:2, three:3};
$.each(anObject, function(name, value) {
 // Do something here
});
Levels