Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Is there any selector to filter the DOM elements based on its content?

Answer»

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  };
2.

How does jqXHR.always() work in an ajax call?

Answer»

.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”);
3.

How to stop a form submit action?

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 NAMEX”.

$("#parent").children( ".x" ).HIDE();
4.

What is $.Deferred () method and how does it work?

Answer»

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>
5.

What is promise and list out few Jquery methods which returns a promise object?

Answer»

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");  })
6.

How to translate a set of values to another set?

Answer»

There are two WAYS to stop a form

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

The sample CODE:

<script>   function formSubmit(){      return false;   } </script> <form onsubmit="return formSubmit();" >
  • 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(); }); })
7.

Is there any function in jquery to filter an array or array-like object?

Answer»

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"
8.

How does .when() method works in jquery?

Answer»

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.

9.

How does jQuery filter () method work and write code to apply css class name for all the links in the page whose host name is not same as the hostname of the site?

Answer»

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;   }
10.

How to select a second item from unordered list and write a mouseover event to it?

Answer»

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);
11.

What does hover() function do in jQuery?

Answer»

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().

12.

How to select all even/odd rows in table?

Answer»

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 &AMP;& a.hostname !== location.hostname  )  .addClass('external');
13.

How to force HTTP GET request to be not cached during ajax call?

Answer»

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.    });
14.

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

Answer»

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(); });
15.

What is the issue with the following code and how to optimize it?

Answer»

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’)
16.

How to handle errors in an ajax request ?

Answer»

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.

17.

How do you iterate a jquery collection?

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.

18.

What is the difference between .attr() vs .prop()?

Answer»

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 );  });
19.

How does jquery .off() work?

Answer»
  • 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 });
20.

How to fire a DOM event manually with jQuery?

Answer»

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".
21.

How does jquery .on() work?

Answer»
  • The .off() METHOD REMOVES event handlers that were attached with .on().
  • Calling .off() with no ARGUMENTS removes all handlers attached to the elements.
<P>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.

22.

Write an event for a menu with id ‘menu’ to show its submenu with id ‘submenu’ on mouseover?

Answer»

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");
23.

How to add an event to an element in jQuery?

Answer»

.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&GT; 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.

24.

Write a query selector to select all the checkboxes in a form in jQuery?

Answer»
  • $(‘#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’ });
25.

What is jqXHR object?

Answer»

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();
26.

What are the main advantages of jquery?

Answer»

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')
27.

What is the current version of jquery and how to include jquery in a html page?

Answer»

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 ) {});
28.

What is the difference between jquery document ready and window.onload event?

Answer»
  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.
29.

How to check if an element has class name “x” ?

Answer»

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>
30.

&lt;div id="parent"&gt;  &lt;Label&gt;Paragraphs&lt;/label&gt;  &lt;p class="x"&gt;Para-x&lt;/p&gt;  &lt;p class="y"&gt;Para-y&lt;/p&gt;  &lt;p class="x"&gt;Para-x&lt;/p&gt; &lt;/div&gt;

Answer»

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  };
31.

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

Answer»

.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”);
32.

How to hide all the child elements with class name “x”?

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 NAMEX”.

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