Share this:

267 Frequently asked jQuery Interview Questions

 

1. What is jQuery?
Answer: jQuery is a client-side JavaScHript framework which helps to traverse  HTML DOM, add Ajax interaction, manipulate the page content, alter the style and offer amazing UI effects.

2. Is jQuery a programming language?
Answer: jQuery is not a programming language but a JavaScript code  is used to event handling, traversing documents, and animation and Ajax interaction.

3. What is the difference between JavaScript and jQuery?
Answer: JavaScript is a language but jQuery is a built-in library made up of JavaScript.  It used to simplify the use of JavaScript language. jQuery is just a JavaScript library used for interacting with HTML and JavaScript. jquery is not the substitute for javascript code.

4. What are uses of jQuery?
Answer:
1.It is used to develop browser compatible web applications.
2.jQuery can enhance the performance of an application.
3.It is fast and extensible.
4.It support a cross-browser support.

5. List some of effects methods used in jQuery?
Answer:
a. animate( params, [duration, easing, callback] ): can make custom animations for HTML elements.
b. fadeIn( speed, [callback] ): can fade in all the matched elements by adjusting their opacity and fires an optional callback after completion.
b. fadeOut( speed, [callback] ): can be used to fade out all the matched elements by adjusting their opacity to 0, after that setting the display to “none” and fires an optional callback after completion.
c. fadeTo( speed, opacity, callback ): can fade the opacity of all the matched elements to a specified opacity and fires an optional callback after completion.
d. stop( [clearQueue, gotoEnd ]): can stop all the currently running animations.
e. Hide(): can hide each set of matched elements if shown.
f. Toggle() : can toggle the elements. It can also toggle the display state of elements between revealed and hidden.
g. Show(): can show each of the matched elements if hidden.

6. Do jQuery HTML work for XML and HTML document?
Answer: jQuery works for HTML and it does not work for HTML document.

7. Name some different types of selectors in jQuery?
Answer: XPath Selector, Custom Selector and CSS Selector.

8. Is jQuery a W3C standard?
Answer: No, jQuery is not a W3C standard.

9. What is $ in JQuery?
Answer: $ is a shortcut to function selector or a JQuery object.
$(document).ready(function(){

});

jQuery(document).ready(function(){

});

10. Can we use Javascript and JQuery on the same page?
Answer: Yes, Javascript and JQuery can be used on the same page. To  use  JQuery we should add.JS library reference to the page, and for JavaScript separate library reference is needed.

11. How to use JQuery?
Answer: To call jquery we should give JQuery library reference to page and then call it using ‘$’ sign

<head>

//JQuery reference

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js”></script>

<script>

$(document).ready(function(){

alert(“Message on on page load”)

});

</script>

</head>

12. What are the features of JQuery?
Answer: Features of jquery are following

  1. Rich Inbuilt methods that easily interact with controls
  2. Events handling
  3. Special widgets
  4. Animation and effect support
  5. Good alternative to flash
  6. Strong AJAX support
  7. HTML DOM Manipulation
  8. Can Bind Multiple Event Handlers in a single method

13. What is JQuery UI?
Answer:  JQuery UI is a JavaScript library which is a user interface portal that is built using JavaScript. It can be easily added in new and existing applications.

It contains interactions, widgets, and effects, to build UI rich and highly interactive applications using it.

14. Which are the performance responsive selector?
Answer: The elements are selected using ID are the performance responsive selector and the ID is unique throughout the rendered page.

15. JQuery or JavaScript which is quicker in execution?
Answer: Native JavaScript is always faster in operation than JQuery because JQuery is a JavaScript library.
Example
$(#EmpName)’ in JQuery, it internally convert the syntax to javascript’s ‘document.getElementById(“EmpName”)’ method and then execute in browser.

16. What is has() in JQuery?
Answer: has() is selection filter to checks Check if an Element ‘Has Something’, means if to traverse my HTML file and check if DIV has list tag (OL) then it can checked with has().

JQuery(‘div’).has(‘ol’);

The code will select all elements with ‘ol’

17. Can JQuery parse XML?                   
Answer: No, JQuery can not support parse XML. It only supports  HTML DOM parser.

18. Can JQuery Run on MAC or Linux instead of Windows?
Answer: JQuery can runs on Windows/MAC/Linux with all major browser compatibility (IE/Chrome/FF/NN/Safari).

19. When to use JQuery?
Answer:  JQuery can be used to create the rich user interface with client-side events to remove flash plugins and put some animations.

20. What is JQuery debugging?
Answer: JQuery can be debugged in following ways
1.Add keyword just before the line where to debug keyword: Add debugger,
2.In visual studio we can place a breakpoint on the line where we want to start debugging,

  1. If we don’t have visual studio, we can place an alert box in lines from where we want to start debugging

21. Can we replace any character or variable instead of $ in JQuery?
Answer: We can replace our own character or variable in place of $ by using the method called no Conflict () method.

var sample = $.noConflict()

22. What is Method chaining in JQuery?
Answer: Method chaining in Jquery is the chain of methods executed in sequence and it is executed in single statement.
snippet
$(“#div1”).text(“DIV 1”);

$(“#div1”).css(“color”, “red”);

$(“#div1”).removeClass(“cls”);

//instead we can write

$(“#div1”).text(“DIV 1”).css(“color”, “red”).removeClass(“cls”);

23. How to redirect a page using JQuery?
Answer: To redirect a page in Jquery Javascript syntex can be used because Jquery does not have any specific syntex to redirect a page.

window.location.replace(“http://test/default.aspx”);

OR

window.location.href = “http://test/default.aspx“;

24. How to check if the element is hidden or visible using JQuery?
Answer:  ‘is()’ method can be used for ‘display’ or ‘hidden’ property, it returns Boolean variable.

$(“#txtEmpName”).is(“:visible”);

25. What is the difference in return false and preventDefault in JQuery?
Answer: While calling return false, it first calls e.preventDefault and after that calls e.stopPropagation that stop the execution. While calling e.preventDefault, it will prevent event to be bubbling up.

26) Explain difference between body onload() and document.ready() function?
Answer: In a page, there can be more than one document.ready() function where there can be only one body onload function.

document.ready() function is called just after DOM is loaded but body.onload() function is called when everything gets loaded on the page  including DOM, images and all other associated resources of the page.

27) What is the difference between .js and .min.js?
Answer: JQuery library has two different versions Development and Production/Deployment. The deployment version is also called as the minified version (.min.js). It is the minified version of the jQuery library file. Both .js and min.js files are same in functionality but .min.js is quite small in size therefore it loads quickly and saves bandwidth. Development version is  useful during development time because jQuery is open source and  changes can be made  in the development version.

28) What is a CDN?
Answer: The goal of content delivery network or content distribution network (CDN) is to serve content to end-users with high availability and high performance. It is a large distributed system of servers deployed in multiple data centres across the Internet.

29) What is the difference between jquery.size() and jquery.length?
Answer: jQuery .size() and .length method returns number of element in the object. But it is not preferred to use the size() method because .length  does not have the overhead of a function call.

30) What is the difference between $(‘div’) and $(‘<div/>’) in jQuery?
Answer: $(‘<div/>’) creates a new div element but this is not added to DOM tree unless it is not append to any DOM element. $(‘div’) selects all the div element present on the page.

31) What is the difference between parent() and parents() methods in jQuery?
Answer: The parent() function can search only one level in the DOM tree but  parents() function can travel through the whole DOM tree.

32) What is the difference between eq() and get() methods in jQuery?
Answer: eq()  method constructs a new jQuery object from one element within that set and returns it and get() method retrieves the DOM elements matched by the jQuery object.  jQuery functions can’t be used because get() is a DOM element and it is not a jQuery-wrapped object.

33) What are selectors in jQuery and how many types of selectors are there?
Answer: Selectors in jquery are used for finding HTML element.
Following are the type of selectors

  1. Name: Selects all elements when it matches with the given element Name
  2. #ID: Selects a single element when it matches with the given ID.
  3. Class: Selects all elements when it matches with the given Class.
  4. Universal (*): Selects all elements which are available in a DOM.
  5. Multiple Elements E, F, G: Multiple elements E,F, G Selects the combined results of all the specified selectors E, F or G.
  6. Attribute Selector: Select elements which matches with its attribute value.

34) How do you select element by ID in jQuery?
Answer: To select element use ID selector by adding prefix “#” (hash symbol) to ID.  Example
to select element with ID “txtName”
$(‘#txtName’)

35) Which are the popular jQuery CDN?
Answer: There are following popular jQuery CDN.
1.Google.
2.Microsoft
3.jQuery.

36) What is the advantage of using CDN?
Answer: Following are the advantage of using CDN
1. It reduces the load on the server.
2.jQuery framework will load faster from these CDN and it will saves bandwidth.
3.It will be cached if the user has visited any site which is using jQuery framework from any of these CDN.

37) How to select element having a particular class (“.selected”)?
Answer: $(‘.selected’). is the class selector. It is needed to be prefix the class name with “.” (dot).

38) What is jQuery.noConflict?
Answer: Other client-side libraries such as MooTools Prototype can be used with jQuery. They use $() as their global function. This situation creates conflict because $() is used by both jQuery and other libraries as their global function.  In jquery jQuery.noConflict()  overcome this problem.

39) What are the fastest selectors in jQuery?
Answer: In jQuery element and ID selectors are the fastest selectors.

40) What are the slow selectors in jQuery?
Answer: Class selectors are the slow in jquery.

41) How jQuery selectors are executed?
Answer: The last selectors are executed first.
Example
$(“p#elmID .myCssClass”);

jQuery will first find all the elements with class “.myCssClass” then it will reject all the other elements which are not in “p#elmID”.

42) Difference between $(this) and ‘this’ in jQuery?
Answer: this and $(this) are the same element. ‘this’ is used in traditional sense, when ‘this’ is used with $() then it becomes a jQuery object.
case 1
$(document).ready(function(){

$(‘#spnValue’).mouseover(function(){

alert($(this).text());

});

});
case 2

$(document).ready(function(){

$(‘#spnValue’).mouseover(function(){

alert(this.innerText);

});

});
In case 2 , ‘this’ is an object but it is not wrapped in $(), therefore we can’t apply jQuery method and use the native JavaScript to get the value of span element.

43) How do you check if an element is empty?
Answer: There are following way to check if element is empty. It  can be checked by using “:empty” selector.

$(document).ready(function(){

if ($(‘#element’).is(‘:empty’)){

//Element is empty

}

});

It can also be checked by “$.trim()” method.

$(document).ready(function(){

if($.trim($(‘#element’).html())==”) {

//Element is empty

}

});

44) How do you check if an element exists or not in jQuery?
Answer: Using jquery length method, it can be checked that if an element exists or not.

$(document).ready(function(){

if ($(‘#element’).length > 0){

//Element Exists

}

});

45) What is the use of jquery.each() function?
Answer: The $.each() function can be used to iterate over any collection of an object or an array.

46) Differentiate between calling stop (true, true) and finish method?
Answer: The .finish() method are same as .stop(true, true) and this can help in clearing the queue and thereby helps the animations to enter into their end state.

47) Explain .bind() vs .live() vs .delegate() vs .on()?
Answer: All these jQuery methods are used for attaching events to selectors or elements.

.bind(): To bind events,  is the easiest and quick method . bind() can attach events to the current elements but not a future element dynamically added element . It has performance problem when dealing with a large selection.

.live(): It can add  dynamically added elements or future elements. It also has poor performance on large pages. Chaining is also not properly supported by this method.

.delegate(): The .delegate() method is similar to the .live() method, but instead of attaching the selector/event information to the document, it can be chosen where it is anchored and it also supports chaining.

.on(): This method provides all the goodness of previous methods and  brings uniformity for attaching event handlers.

48) How to create clone of any object using jQuery?
Answer: jQuery provides clone() method which copies the matched elements along with all of their descendant elements and text nodes.

$(document).ready(function(){

$(‘#btnClone’).click(function(){

$(‘#dvText’).clone().appendTo(‘body’);

return false;

});

});

49) Does events are also copied when you clone an element in jQuery?
Answer:  clone() method creates clone of any element but to copy the events, true should be passed as parameter in clone() method.

$(document).ready(function(){

$(“#btnClone”).bind(‘click’, function(){

$(‘#dvClickme’).clone(true).appendTo(‘body’);

});

50) What is difference between prop and attr?
Answer: attr() provides the value of element as it was defined in the HTML on page load. It is recommended to use prop() to get values of elements that is modified via javascript/ jquery, as it provides the original value of an element’s current state.

51) What is event.PreventDefault?
Answer: The event.preventDefault() method can stop the default action of an element. It can prevent a link from following the URL.

52) What is the difference between event.PreventDefault and event.stopPropagation?
Answer: event.preventDefault():It can  stop the default action of an element.

event.stopPropagation(): It can prevent the event from bubbling up the DOM tree, and it also prevents any parent handlers from being notified of the event.

53) What is the difference between event.PreventDefault and “return false”?
Answer: e.preventDefault() can prevent the default event from occurring, e.stopPropagation() can prevent the event from bubbling up and return false can do both.

54) What is the difference between event.stopPropagation and event.stopImmediatePropagation?
Answer: event.stopPropagation() can allow other handlers on the same element to be executed, and event.stopImmediatePropagation() can prevent every event from running.

55) How do you attach an event to the element which should be executed only once?
Answer: jQuery one() method can attache a handler to an event for the element. It is executed at most once per element, it means attached function will be called only once.

$(document).ready(function() {

$(“#btnDummy”).one(“click”, function() {

alert(“This will be displayed only once.”);

});

});

56) How to disable cut,copy & paste in TextBox using jQuery?
Answer: Syntex

<script type=”text/javascript”>

$(document).ready(function (){

$(‘#txt_employee_code’).bind(‘copy paste cut’,function(e){

e.preventDefault();

});

});

</script>

57)How to retrieve the Number of Rows in a Gridview through jQuery?
Answer: The syntex is

var grid_row_count = $(‘#grid_view_id tr’).length;

58) How to attach keydown event to an element in jquery?
Answer: syntex

<script type=”text/javascript”>

$(“#txtKeyPress”).keydown(function (){

$(“#div3″).append(” | key DOWN event fired”);

});

</script>

59) How to disable Browser Back button through jQuery?
Answer: syntex

<script type=”text/javascript” language=”javascript”>

$(document).ready(function() {

window.history.forward(1);

//OR

window.history.forward(-1);

});

</script>

60) How to disable mouse right click using jQuery?
Answer: Syntex

<script type=”text/JavaScript”>

$(function(){

$(this).bind(“contextmenu”, function(e){

e.preventDefault();

});

});

</script>

61) Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?
Answer: jQuery.ajax() is jQuery’s low-level AJAX implementation and $.get and $.post are higher-level abstractions which are often easier to use but it don’t has  much functionality like error callbacks.

62) How will you Encode/Decode URL in jQuery ?
Answer: In following way functions can be encoded and decoded url in jquery

1.encodeURIComponent(url)

2.decodeURIComponent(url)

63) Define Find and Children Method?
Answer: In DOM tree, Find Method is used to find all the method and Children Method is used to find single level.

64) Is it necessary to add jQuery file in Master as well as Content page?
Answer: No, if jQuery file is added in Master page then content page can be directly accessed.

65) How to add or remove specified class if not present?
Answer: Specified class can be add or removed by using toggleClass(class) function.

66) What is jQuery connect?
Answer: A jQuery connect can be used for executing function from any other function or plugin is executed. It can be used to connect or bind a function with another function.

67) What is the use of jQuery.data method?
Answer: jQuery.data methods can be used for associating the data with the DOM nodes and the objects. It can make the jQuery code clear and concise.

68) What is the use of jQuery load method?
Answer: jQuery load method is a AJAX method that is used  for loading the data from a server. It assign the data into the element without loading the page.

69) What is the use of jQuery filter?
Answer: The jQuery filter can be used for filtering the certain values from the object list based on the criteria. For example it can filter certain products from the master list of products in a cart website.

70) What is used for testing jQuery?
Answer: To test jQuery, QUnit is used. It is very easy and efficient.

71)What is the script build up by jQuery?
Answer: jQuery can build a JavaScript file which contains common DOM, event effects and Ajax functions.

72) What are method to include jQuery in a page?
Answer: In following ways jQuery can be included in a page:

  1. Remote copy of jQuery.com.
  2. Local copy inside script tag.
  3. Local copy of script manager control.
  4. Remote copy of Ajax API.
  5. Embedded script using client script object.

73) Which method is used to switch between adding/removing one or more classes (for CSS) from selected elements?
Answer: The switchClass method can be used for adding and removing the specified classes to each of the set of matched elements while animating all style changes.
It can also move from one CSS class to another CSS class, animating the transition from one state to another state.
Syntax:
.switchClass( removeClassName, addClassName [, options ] )

Parameters:
removeClassName: This string parameter represents the CSS class name or space demarcated list of class names, to be removed.
addClassName: This type string represents one or more class names which are added to the class attribute of each matched element.
options: It is used for specifying all animation settings.

74) What does $(“div.parent”) will select?
Answer: $(“div.parent”) will select all the div element with the parent class.

75) Where jQuery code is getting executed?
Answer: jQuery code can be executed on a client browser.

76) How to load jQuery from CDN?
 Answer: Code to load CDN from Google :
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
Code to load CDN from Microsoft :
<script src=”https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js”></script>

77) jQuery library is server scripting or client scripting ?
Answer: The  jQuery library is not a server scripting, it is a client side Scripting.

78) Explain the ways to read, write and delete cookies in jQuery .
Answer: The ftl cookie plugin can handle cookies in jquery.
1.To create cookie we can use $.ftl(“cookie_name”, “cookie_value”);
2.To read cookie we can use $.ftl(“cookie_name”);
3.To delete cookie we can use $.ftl(“cookie_name”, “remove”);

79) What are the four parameters used for jQuery Ajax method ?
Answer: The following four parameters are used for jquery Ajax method.
1.URL : It is required to specify the URL to send the request.
2.type : It is required to Specify type of request(Get or Post).
3.data :It is required to Specify data to be sent to server.
4.Cache :It is required whether the browser should cache the requested page.

80) What is the use of hide() method in jQuery?
Answer: We can hide selected HTML elements using hide() method.
Syntax:
$(selector).hide(speed,easing,callback)

Parameters”
Speed: The speed of the hide effect specified by speed and the default value of speed is 400 milliseconds. Possible values are: milliseconds, slow, fast.
Easing: The speed of the element in different points of the animation are specified by easing. The default value of easing  is “swing” and the possible values are swing and linear.
Callback: A function to be executed after the hide() method is completed is specified by Callback.

81) What is the use of NoConflict method in jQuery?
Following are the use of noConflict method
Answer:
1.noConflict() method can help to make sure that jQuery should not conflict with the $ object of other libraries.
2.It method can release the hold on the $ shortcut identifier free, to be used by other scripts.
3.A new custom name for the jQuery variable can also be specify noConflict method.
Syntax:
$.noConflict(removeAll)

Parameters:
removeAll is a boolean value which specifies whether to release or not  jQuery’s control of ALL jQuery variables. It is a optional parameter.

82)  Is jQuery a replacement of JavaScript?
Answer:  jQuery is not a replacement of JavaScript because JavaScript is a full-fledged scripting language and jQuery is a specific implementation of JavaScript library. It can compile and interpret with the JavaScript compiler and interpreter.
Therefore it can be said that jQuery is for the assisting JavaScript and not for replacing Javascript.

83) What is the difference between Hover and Mouseover?
Answer: When the mouse pointer hovers over the selected elements, it specifies two functions to run whether Mouseover occurs when the mouse pointer is over the selected element.
The hover() method can triggers  the mouseenter and mouseleave events but
The mouseover() method can triggers the mouseover event or attaches a function to run.

Syntax hover :
$(selector).hover(inFunction,outFunction)

Parameters:
inFunction specify the function to run when the mouseenter event occurs .

OutFunction specify the function to run when the mouseleave event occurs.

Syntex mouseover:
To trigger the mouseover event for the selected elements:

$(selector).mouseover()

To attach a function to the mouseover event:

$(selector).mouseover(function)

Parameters,

function specifies the function to run when the mouseover event is triggered.

84) Why is jQuery library used for client scripting?
Answer: jQuery libraries of JavaScript is used because of its extremely easy syntax for performing tedious task like Ajax calls and DOM manipulation.
It can help to build robust and modern web applications in very short span of time.

85)What is meant by deep copy?
Answer: Deep copy method copies all fields, and makes copies of dynamically allocated memory pointed by the fields. Deep copy can create a deep copy of the set of matched elements. This will occur when an object is copied along with the objects to which it refers.
The .clone() method Will perform a deep copy of the set of matched elements

The $.extend method is used here  to perform deep copy in JavaScript object.
Syntax:
$.extend(deepCopy, target, object1, [objectN] )
deepCopy: This parameter is used for performing deep copy. It indicates first argument as true.
target: To copy everything into.
object 1object2: To copy from.

86) What do we know about .promise() method in jQuery?
Answer: The .promise() method can return a promise object for observing when all the actions of a certain type bound to the collection, queued or not, are finished.
Syntax:

.promise( [type ] [, target ] )
The .promise() method takes two arguments:
a. type: By default, this is “fx”, that means the returned promise is resolved when all animations of the selected elements are.
b. target: .promise() will attach to target , If a target object is specified. Then return the object and not create a new one

87) How to check jQuery version using jQuery method?
Answer: Version can be checked using following syntex
$.ui.version

88) What are the basic selectors in jQuery?
Answer: Following are basic selectors in jQuery for selecting HTML element and do operation on it.

Element ID //#eleID

CSS Name //.eleClassname
DOM hierarchy
Tag Name // text

89) What is jQuery wildcard selector?
Answer: Wildcard is referred to the special charterer that used to select all elements based on substring. For example, we have to select all elements into a page which are started with ‘div_’ string.

90) How to use selector caching in jQuery?
Answer: The process to store one time element object into a variable and use this variable repeatedly whenever it is required,  is called selector caching in jQuery.

91) What is prevent event bubbling in Jquery?
Answer: jQuery can provide ‘event.stopPropagation’ method for stoping event bubbling.

92) In what cases jQuery can be used?
Answer: jQuery can be used in following Cases
1.Apply CSS static or dynamic
2. Mainly for Animation effects
3.Manipulation purpose
4.Calling functions on events

93) How to get custom element attribute data in jQuery?
Answer: jQuery can provide jQuery.data() method for getting and setting element attribute value.

<input type=”text” data-id=”test” id=”testId” />

$(‘#testId’).data(‘data-id’);

1

2

<input type=”text” data-id=”test” id=”testId” />

$(‘#testId’).data(‘data-id’);

The Line #1 is use for defining attribute data-id into input element.

94) Which operating system is more compatible with jQuery?
Answer: Mac, Windows and Linux

95) How can we include jQuery library in ASP.Net project?
Answer: To include jQuery library in ASP.Net project
1. From jQuery.com, download the jQuery library.
2.Include the reference in the asp.net page.

96) Is jQuery is a JavaScript or JSON library file?
Answer: jQuery is a library is single JavaScript file and it has DOM, event effects and the Ajax functions.

97) What are the features of jQuery, has been used in web applications?
Answer: In web application, jQuery can use features such as Sliding, File uploading and accordian in web applications.

98) What are the browser related issues for jQuery?
Answer:  Issue for jQuery is browser compatibility of jQuery plugin  and needs lot of time to fix it.

99) Can we call C# code behind using jQuery?
Answer: Yes, we can call C# code from jQuery because it supports .net application.

100) Where can we download JQuery?
Answer: From jQuery official website – www.jquery.com jQuery javascript can be downloaded.

101)How method can be called inside code behind using jQuery?
Answer: $.ajax is called and declared by WebMethod inside code behind using jQuery.

102) Where jQuery code is getting executed?
Answer: On client browser jQuery is executed.

103) Who has developed JQuery?
Answer: JQuery has been developed by John Resig.

104) What is current stable release of jquery?
Answer: 3.4.1 is current stable release of jquery.

105) What are the various ajax functions available in Jquery ?
Answer:Following functions are available in jquery
1.$.ajax(): This is low level and basic of functions to send requests .  It is performed without a selector.
2.$.ajaxSetup(): It can be used for defining and set the options for various ajax calls.

For example.

$.ajaxSetup({

“type”:”POST”,

“url”:”ajax.php”,

“success”:function(data){

$(“#bar”)

.css(“background”,”yellow”)

.html(data);

}

});

3.Shorthand ajax methods: It is comprised of simply the wrapper function which call $.ajax() with certain parameters already set.

4.$.getJSON(): It is a type of shorthand function that is used for accepting the url to which the requests are sent.

106) What is the use of param() method in JQuery .
Answer: The param() method is used for representing an array or an object in serialize manner.
We can use these serialize values in the query strings of URL while making an ajax request.
Syntax:

$.param(object | array, boolValue)

“object | array” specifies an array or an object which is to be serialized.

“boolValue” It specify whether to use the traditional style of param serialization or not.

107) How can events be prevented from stopping to work after an ajax request?
Answer: Events can be prevented from stopping to work after an ajax request.
Use of event delegation: The event delegation technique uses event bubbling to capture the events on elements that are present anywhere in the domain object model.
Example:
handling even delegation, handling of clicks on any <a> element:

$(‘#mydiv’).click(function(e){

if( $(e.target).is(‘a’) )

fn.call(e.target,e);

});

$(‘#mydiv’).load(‘my.html’)

Event rebinding usage: This method requires the user to call the bind method and the added new elements.

$(‘a’).click(fn);

$(‘#mydiv’).load(‘my.html’,function(){

$(‘#mydiv a’).click(fn);

});

108) How can we create an Object in JavaScript?
Answer: JavaScript supports Object concept and it can create an object using the object literal.
var emp = {

name: “Rima”,

age: 20

};

109) How can we read properties of an Object in JavaScript?
Answer: Properties of an object can be written and read by using the dot notation.
// get object properties

emp.name  // ==> Rima

emp.age   // ==> 20

 

// Set object properties

emp.name = “Dolly”  // <== Dolly

emp.age  =  25      // <== 25

110) How can we create an Array in JavaScript?
Answer: Define arrays using the array literal as described below.
var x = [];

var y = [1, 3, 5, 7, 9];

111) How to read elements of an array in JavaScript?
Answer: Length property of an array is useful for iteration. Elements of an array can be read as described below:

var x = [1, 2, 3, 4, 5];

 

for (var i = 0; i < x.length; i++) {

// Do something with x[i]

}
112) What is a named function in JavaScript? How to define a named function?
Answer: If a function has a name when it is defined is called named function. A named function are defined using function keyword :

function named(){

// do some stuff here

}

113) How many types of functions JavaScript supports?
Answer: A function in JavaScript are 1. named or 2.anonymous.

114) How to define a anonymous function?
Answer: An anonymous function are defined as a normal function but without  any name.

115) Can we assign a anonymous function to a variable?
Answer: We can assign An anonymous function to a variable.

116) Can we pass a anonymous function as an argument to another function?
Answer: We can pass an anonymous function as an argument to another function.

117) What is arguments object in JavaScript?
Answer: JavaScript variable arguments passed to a function.

118) How can we get the type of arguments passed to a function?
Answer: We can get the type of arguments passed to a function  typeof operator.
function func(x){
console.log(typeof x, arguments.length);
}

func();                //==> “undefined”, 0
func(1);               //==> “number”, 1
func(“1”, “2”, “3”);   //==> “string”, 3

119) How can we get the total number of arguments passed to a function?
Answer: We can get the total number of arguments passed to a function using arguments.length property.
function func(x){
console.log(typeof x, arguments.length);
}
func();                //==> “undefined”, 0
func(1);               //==> “number”, 1
func(“1”, “2”, “3”);   //==> “string”, 3

120) How can we get the reference of a caller function inside a function?
Answer: We can get the reference of a caller function inside a function using callee property
function func() {
return arguments.callee;
}
func();                // ==> func

121) What are the valid scopes of a variable in JavaScript?
Answer: The scope of a variable is the region of the program in which it is defined. JavaScript variable has only following scopes.

Global Variables has global scope that means it is visible everywhere in JavaScript code.

Local Variables will be visible only within a function where it is defined and  parameters are always local to the function.

122) Which type of variable among global and local, takes precedence over other if names are same?
Answer: A local variable takes precedence over a global variable if  the name is similar.

123) What is callback?
Answer: A callback JavaScript function is passed to some method as an argument or option. Some callbacks are events which called to give the user a chance to react when a certain state is triggered.

124) What is closure?
Answer: A variable which is defined outside the current scope is accessed from within some inner scope, closures are created.

125) Give an example of closure?
Answer: Following is an example of closure. It shows that the variable counter is visible within the create, increment, and print functions, but not outside of them −

function create() {

var counter = 0;

 

return {

increment: function() {

counter++;

},

print: function() {

console.log(counter);

}

}

}

var c = create();

c.increment();

c.print();     // ==> 1

126) Which built-in method returns the character at the specified index?
Answer: charAt() method can return the character at the specified index.

127) Which built-in method combines the text of two strings and returns a new string?
Answer: concat() method can return the character at the specified index.

128) Which built-in method calls a function for each element in the array?
Answer: forEach() method can call a function for each element in the array.

129) Which built-in method returns the index within the calling String object of the first occurrence of the specified value?
Answer: indexOf() method can return the index within the calling String object of the first occurrence of the specified value, or −1 if not found.

130) Which built-in method returns the length of the string?
Answer: length() method can return the length of the string.

131) Which built-in method removes the last element from an array and returns that element?
Answer: pop() method can remove the last element from an array and can return that element.

132) Which built-in method adds one or more elements to the end of an array and returns the new length of the array?
Answer: push() method can add one or more elements to the end of an array and can return the new length of the array.

133) Which built-in method reverses the order of the elements of an array?
Answer: reverse() method can reverse the order of the elements of an array — It changes first to the last, and the last to the first.

134) Which built-in method sorts the elements of an array?
Answer: sort() method can sort the elements of an array.

135) Which built-in method returns the characters in a string beginning at the specified location?
Answer: substr() method can return the characters in a string beginning at the specified location through the specified number of characters.

136) Which built-in method returns the calling string value converted to lower case?
Answer: toLowerCase() method can return the calling string value converted to lower case.

137) Which built-in method returns the calling string value converted to upper case?
Answer: toUpperCase() method can return the calling string value converted to upper case.

138) Which built-in method returns the string representation of the number’s value?
Answer: toString() method can return the string representation of the number’s value.

139) How to select elements using jQuery with the given element tag-name?
Answer: $(‘tag-name’) can select all element of type tag-name in the document. Such as $(‘p’) selects all paragraphs <p> in the document.

140) How to select single element using jQuery with the given element id some-id?
Answer: $(‘#some-id’) can select the single element in the document that has an ID of some-id.

141) How to select elements using jQuery whose css class is some-class?
Answer: $(‘.some-class’) can select all elements in the document that has a class of some-class.

142) How to select all Following elements using jQuery?
Answer: $(‘*’) use to select all elements available in a DOM.

143) How to get attributes of an element using jQuery?
Answer: The attr() method is used to fetch the value of an attribute from the first element in the matched set.

144) How to set attributes of an element using jQuery?
Answer: The attr(name, value) method are used for setting the named attribute onto all elements in the wrapped set using the passed value.

145) How can we apply a style on an element using jQuery?
Answer: The addClass( classes ) method are used for applying defined style sheets onto all the matched elements. We can specify multiple classes separated by space.

146) How to remove an attribute from each of the matched elements using jQuery?
Answer: The removeAttr( name ) method are used for removing an attribute from each of the matched elements.

147) How to know if a specified class is present on at least one of the set of matched elements using jQuery?
Answer: The hasClass( class ) method can return true, if the specified class is present on at least one of the set of matched elements.

148) How to remove all or the specified class(es) from the set of matched elements using jQuery?
Answer: The removeClass(class) method can remove all or the specified class(es) from the set of matched elements.

149) How to add the specified class if it is not present, remove the specified class if it is present using jQuery?
Answer: The toggleClass(class) method can add the specified class if it is not present, and can remove the specified class if it is present.

150) How to get the html contents (innerHTML) of an element using jQuery?
Answer: The html() method can get the html contents (innerHTML) of the first matched element.

151) How to set the html contents of an element using jQuery?
Answer: The html( val ) method can set the html contents of every matched element.

152) How to get the text contents of an element using jQuery?
Answer: The text( ) method can get the combined text contents of all matched elements.

153) How to set the text contents of an element using jQuery?
Answer: The text( val ) can set the text contents of all matched elements.

154) How to get the input value of an element using jQuery?
Answer: The val( ) method can get the input value of the first matched element.

155) How to set the value of an element using jQuery?
Answer: The val(val) method can set the value attribute of every matched element if it is called on <input>.  If it is called on <select> along with the passed <option> value then passed option will be selected. If it is called on check box then all the matching check box will be checked.

156) How to reduce the set of matched elements to a single element using jQuery?
Answer: The eq( index ) method can reduce the set of matched elements to a single element.

157) How to checks the current selection against an expression using jQuery?
Answer: The is( selector ) method can check the current selection against an expression and it returns true, for at least one element of the selection fits the given selector.

158) How to removes elements matching the specified selector from the set of matched elements using jQuery?
Answer: The not(selector) method can remove elements matching the specified selector from the set of matched elements.

159) How to select a subset of the matched elements using jQuery?
Answer: The slice(selector) method can select a subset of the matched elements.

160) How to add more elements, matched by the given selector, to the set of matched elements using jQuery?
Answer: The add( selector ) method can add more elements, matched by the given selector, to the set of matched elements.

161) How to add the previous selection to the current selection using jQuery?
Answer: The andSelf( ) method can add the previous selection to the current selection.

162) How to get a set of elements containing all of the unique immediate children of each of the matched set of elements using jQuery?
Answer: The children( [selector]) method can get a set of elements containing all of the unique immediate children of each of the matched set of elements.

163) How to get a set of elements containing the closest parent element that matches the specified selector, the starting element included using jQuery?
Answer: The closest( selector ) method can get a set of elements Which  contains the closest parent element that matches the specified selector, the starting element included.

164) How to find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe using jQuery?
Answer: The contents( ) method can find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.

165) How to revert the most recent ‘destructive’ operation, changing the set of matched elements to its previous state using jQuery?
Answer: The end( ) method can revert the most recent ‘destructive’ operation, changes the set of matched elements to its previous state.

166) How to search for descendent elements that match the specified selectors using jQuery?
Answer: The find( selector ) method can search for descendent elements that match the specified selectors.

167) How to get a set of elements containing the unique next siblings of each of the given set of elements using jQuery?
Answer: The next( [selector] ) can get a set of elements Which contain the unique next siblings of each of the given set of elements.

168) How to find all sibling elements after the current element using jQuery?
Answer: The nextAll( [selector] ) can find all sibling elements after the current element.

169) How to get a jQuery collection with the positioned parent of the first matched element?
Answer: The offsetParent( ) method can return a jQuery collection with the positioned parent of the first matched element.

143) How to get attributes of an element using jQuery?
Answer: The attr() method is used to fetch the value of an attribute from the first element in the matched set.

144) How to set attributes of an element using jQuery?
Answer: The attr(name, value) method are used for setting the named attribute onto all elements in the wrapped set using the passed value.

145) How can we apply a style on an element using jQuery?
Answer: The addClass( classes ) method are used for applying defined style sheets onto all the matched elements. We can specify multiple classes separated by space.

146) How to remove an attribute from each of the matched elements using jQuery?
Answer: The removeAttr( name ) method are used for removing an attribute from each of the matched elements.

147) How to know if a specified class is present on at least one of the set of matched elements using jQuery?
Answer: The hasClass( class ) method can return true, if the specified class is present on at least one of the set of matched elements.

148) How to remove all or the specified class(es) from the set of matched elements using jQuery?
Answer: The removeClass(class) method can remove all or the specified class(es) from the set of matched elements.

149) How to add the specified class if it is not present, remove the specified class if it is present using jQuery?
Answer: The toggleClass(class) method can add the specified class if it is not present, and can remove the specified class if it is present.

150) How to get the html contents (innerHTML) of an element using jQuery?
Answer: The html() method can get the html contents (innerHTML) of the first matched element.

151) How to set the html contents of an element using jQuery?
Answer: The html( val ) method can set the html contents of every matched element.

152) How to get the text contents of an element using jQuery?
Answer: The text( ) method can get the combined text contents of all matched elements.

153) How to set the text contents of an element using jQuery?
Answer: The text( val ) can set the text contents of all matched elements.

154) How to get the input value of an element using jQuery?
Answer: The val( ) method can get the input value of the first matched element.

155) How to set the value of an element using jQuery?
Answer: The val(val) method can set the value attribute of every matched element if it is called on <input>.  If it is called on <select> along with the passed <option> value then passed option will be selected. If it is called on check box then all the matching check box will be checked.

156) How to reduce the set of matched elements to a single element using jQuery?
Answer: The eq( index ) method can reduce the set of matched elements to a single element.

157) How to checks the current selection against an expression using jQuery?
Answer: The is( selector ) method can check the current selection against an expression and it returns true, for at least one element of the selection fits the given selector.

158) How to removes elements matching the specified selector from the set of matched elements using jQuery?
Answer: The not(selector) method can remove elements matching the specified selector from the set of matched elements.

159) How to select a subset of the matched elements using jQuery?
Answer: The slice(selector) method can select a subset of the matched elements.

160) How to add more elements, matched by the given selector, to the set of matched elements using jQuery?
Answer: The add( selector ) method can add more elements, matched by the given selector, to the set of matched elements.

161) How to add the previous selection to the current selection using jQuery?
Answer: The andSelf( ) method can add the previous selection to the current selection.

162) How to get a set of elements containing all of the unique immediate children of each of the matched set of elements using jQuery?
Answer: The children( [selector]) method can get a set of elements containing all of the unique immediate children of each of the matched set of elements.

163) How to get a set of elements containing the closest parent element that matches the specified selector, the starting element included using jQuery?
Answer: The closest( selector ) method can get a set of elements Which  contains the closest parent element that matches the specified selector, the starting element included.

164) How to find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe using jQuery?
Answer: The contents( ) method can find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.

165) How to revert the most recent ‘destructive’ operation, changing the set of matched elements to its previous state using jQuery?
Answer: The end( ) method can revert the most recent ‘destructive’ operation, changes the set of matched elements to its previous state.

166) How to search for descendent elements that match the specified selectors using jQuery?
Answer: The find( selector ) method can search for descendent elements that match the specified selectors.

167) How to get a set of elements containing the unique next siblings of each of the given set of elements using jQuery?
Answer: The next( [selector] ) can get a set of elements Which contain the unique next siblings of each of the given set of elements.

168) How to find all sibling elements after the current element using jQuery?
Answer: The nextAll( [selector] ) can find all sibling elements after the current element.

169) How to get a jQuery collection with the positioned parent of the first matched element?
Answer: The offsetParent( ) method can return a jQuery collection with the positioned parent of the first matched element.

170)How to get the direct parent of an element using jQuery?
Answer: The parent( [selector] ) method can get the direct parent of an element. If called on a set of elements, parent can return a set of their unique direct parent elements.

171) How to get a set of elements containing the unique ancestors of the matched set of elements using jQuery?
Answer: The parents( [selector] ) method can get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).

172) What are various methods to make ajax request in jQuery ?
Answer: We can make ajax calls, using below jQuery methods,

1.load() : It loads a piece of html into a container DOM
2.$.getJSON() : It loads JSON with GET method.
3.$.getScript() : It loads a JavaScript file.
4,$.get() :  It is used to make a GET call and play extensively with the response.
5,$.post() : It is used to make a POST call and don’t want to load the response to some container DOM.
6.$.ajax() : It is used  do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.

173) How to get custom element attribute data in jQuery?
Answer: jQuery can provide jQuery.data() method for getting and setting element attribute value.

<input type=”text” data-id=”test” id=”testId” />

$(‘#testId’).data(‘data-id’);

1

2

<input type=”text” data-id=”test” id=”testId” />

$(‘#testId’).data(‘data-id’);

174) How can you disable jQuery animation?
Answer: We can disable jQuery animation by using jQuery property “jQuery.fx.off”  and set it to true.

175) What is the purpose of fadeToggle() method in JQuery?
Answer: jQuery fadeToggle() method is used for toggling between the fadeIn() and fadeOut() methods.
$(selector).fadeToggle();

$(selector).fadeToggle(speed,callback);

$(selector).fadeToggle(speed, easing, callback);

176) What is the use of delay() method in JQuery?
Answer: The jQuery delay() method can be used for delaying the execution of functions in the queue. It sets a timer to delay the execution of the next item in the queue.
$(selector).delay (speed, queueName)

177) What is the starting point of code execution in jquery?
Answer: $(document).ready() function is executed when DOM is loaded and it is the starting point of jQuery code.

178) What is the basic requirement to start with the jQuery?
Answer: The basic requirement to start with jquery:
1. Refer to library to start with jquery.
2.download the latest version from jquery.com

179) What is the use of serialize() method in JQuery?
Answer: The jQuery serialize() method is used for create a text string in standard URL-encoded notation and serializes the form values  in a way that it can be used in the URL query string to make an AJAX request.

$(document).ready(function(){
$(“button”).click(function(){

$(“div”).text($(“form”).serialize());
});

});

180) What is the use of val() method in JQuery?
Answer:   The jQuery val() method has following application:

1.To get the current value of the first element in the set of matched elements.
2.To set the value of every matched element.
$(document).ready(function(){
$(“button”).click(function(){
$(“div”).text($(“form”).serialize());
});

});

181) Can you write a jQuery code to select all links inside the paragraph?
Answer: We can use <a> tag nested inside paragraph <p> tag for selecting all links.

<!DOCTYPE html>

<html>

<head>

<title>jQuery Example</title>

<script type=”text/javascript” src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”>

</script>

<script type=”text/javascript” language=”javascript”>

$(document).ready(function()

{

$(“p a”).attr(“href”, “https://www.javatpoint.com”);

});

</script>

</head>

<body>

<p><a>Learn JavaScript</a></p>

<p><a>Learn jQuery</a></p>

</body>

</html>

182) What is the use of the animate() method in jQuery?
Answer: The animate function is used for applying the custom animation effect to elements.
$(selector).animate({params}, [duration], [easing], [callback])

183) Explain the ways through which we can include jQuery on a page?
Answer:  jQuery in a page can be done by the following ways. 
1.Local copy inside script tag
2.Embedded script using client script object
3.By keeping a remote copy of Ajax API
4.Making a local copy of script manager control
5.Remote copy of jQuery.com

184) Explain the Struts2 jQuery plug-in and its advantages.
Answer: The struts2 jQuery plug-in has application in
1.Easy integration of Ajax and widgets are provided to the user.
2.The extent of coding needed are reduced.
Example
Result Div

Following are the advantage of jQuery struts2:
1. reduced the extent of coding needed for a particular action.
2.Supports ajax form validation.
3.The readability levels of the code is high and therefore it is much easier to perform the debugging.

185) Explain how the jQuery stores data related to an element?
Answer: Information of an element are stored in the simple javascript by adding a domain object model property to the element and this can lead to issues such as leakage of memory in the browsers.

In  jQuery the memory management issues are solved.
Example

Storing and retrieving data
$(‘#myDiv’).data(‘keyName’, { foo : ‘bar’ });

$(‘#myDiv’).data(‘keyName’); // { foo : ‘bar’ }

186) Describe the procedure of extracting a query string with regular expressions?
Answer: The procedure of extracting a query string with regular expressions are done in following ways.

  1. Approach of String-based: 

Approach of string-based method is carried ahead by making the utilisation of the .replace() method to function and is simplest way in use for extracting a query string with regular expressions. This

Example
var data = string.replace(“http://localhost/view.php?”, “”);

2. Regular expression approach:

Regular expression approach pattern must be used that seeks about the question mark among the string and the most powerful method for extracting a query string.

187) Explain the concept of Grouping?
Answer: The concept of grouping are explained as whenever the same declaration gets shared by more than one selector. They get separated by a common separated list and it helps in reducing the size of the CSS and make it
more readable.

188) What is the procedure to check the data type of any variable in jQuery?
Answer: The data type of any variable in jQuery can be checked by $.type(Object) which returns the built-in JavaScript type for the object.

189) Write jQuery code to select all the paragraphs in the page.
Answer: Syntex:

var elems = $(“p”);
The elems variable can hold zero or more paragraphs depending on the number of paragraphs available in the web page.

190) What is slice() method in jQuery?
Answer: Slice() method can select a subset of the matched elements by providing a range of indices. And It gives the set of DOM elements on the basis of the parameter (start, end).

Syntax: .slice( start, end[Optional] )

Start is the first and mandatory parameter and it specifies from where to start to select the elements.

End is an optional parameter to indicates where to stop the selection of elements, excluding end element and it specifies the range of the selection.

191) Explain the concept of writing the browser specific code using jQuery?
Answer: Browser specific code can be written by simply making use of the jQuery browser property which contains flags for the user agent, read from navigator.userAgent.

This property was removed from jQuery 1.9.

192) What is the difference between .empty(), .remove() and .detach() methods in jQuery?
Answer: These method are used for removing DOM
.empty(): Removes all the child element of the matched element.
.remove(): Removes the element itself along with everything inside it. In addition to the elements, events and jQuery data associated with the elements are removed.

.detach():  .remove(), and .detach() are same except it keeps all jQuery data associated with the removed elements. This is useful when removed elements are to be reinserted into the DOM at a later time.

193) What is the difference in return false and preventDefault in JQuery?
Answer: While  calling return false, it first calls e.preventDefault and after that calls e.stopPropagation that stop the execution. While calling e.preventDefault, it will prevent event to be bubbling up.

194) What is the difference between “#” and “.” selector in JQuery?
Answer: # is a specific ID selector which can select element having ID as ‘btnSubmit’ and “.”  is a specific Class selector which can select element having class as ‘classBold’.

195) Which are the most common JQuery events?
Answer:
1.click (): Raised by clicking an element.
2.dblclick(): Raised by double clicking an element.
3.mouseenter(): Raised by entering mouse pointer in an element.
4.mouseleave():Raised when mouse pointer leaves an element. mousedown(): 5.Raised when mouse pointer clicked down on an element
6.mouseup(): Raised when mouse pointer clicked and release on an element
7.focus(): Raised when an element got focus

196) What is jQuery UI Sortable and how to use it?
Answer: Using jquery UI sortable the DOM elements in the defined area can be reorder. To arrange item, have to click on the item and dragged that item to a new place and all other items are automatically arranged.
Following procedure to enable sortable elements:
Include the jQuery js file.

<script src=”https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js”></script>
Include the jQuery UI js file.
<script src=”https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js” type=”text/javascript”></script>

197) Define jQuery UI Autocomplete ?
Answer: Autocomplete is widgets ON websites which is used in nearly all websites. To call to build and bind a list (server-side) into a text box using JavaScript jQuery-ui autocomplete is the most robust and efficient tool of autocomplete and it is also free.

198) What is the usage of Draggable, Droppable, Resizable, Selectable in jQuery UI?
Answer: There are following plugins available in the interaction section

Draggable:  It can move the draggable object by clicking on it and dragging it anywhere within the viewport.

Droppable: Droppable can enable any DOM element to be droppable.

Resizable: It can enable any DOM element to be resizable. Resize with the cursor by grabbing the right or bottom border and drag to the desired width or height.

Selectable: It can enable a DOM element (or group of elements) to be selectable. It can Draw a box with  cursor to select items and it can Hold down the Ctrl key to make multiple non-adjacent selections.

Sortable: It can enable a group of DOM elements to be sortable. By Clicking on and dragging an element to a new spot within the list, and then other items will adjust to fit. By default, sortable items share draggable properties.

199) What is the jQuery Unbind() method?
Answer: The jQuery unbind() removes an existing event handler from elements.

200) What is an attribute in jQuery?
Answer: Following are an attribute in jquery.

  1. attr( properties ) – It can set a value object as properties for all matching
  2. attr( key, fn ) – It can set a single property to a computed value, on all matching
  3. removeAttr( name ) – It can remove an attribute from each of the matched elements.
  4. hasClass( class ) -It can return true if the specified class is present on at least one of the set of matched elements else return false
  5. removeClass( class ) -It can removes all or the specified class(es) from the set of matched elements.
  6. toggleClass( class ) – It can add the specified class if it is not present, removes the specified class if it is present.
  7. html( ) – It can get the innerHTML contents of the first matched element.
  8. html( val ) – It can set the HTML contents of every matched element.
  9. text( ) – It can get the combined text contents of all matched elements
  10. text( val ) – It can Set the text contents of all matched elements
  11. val( ) – It can the input value of the first matched element.

201) What are the various type of filters supported by jQuery?
Answer: JQuery supports following types of filters
1..eq()
2.first()
3.last()
4.filter()
5.has()
6.not()

202) Define bind() elements in jQuery?
Answer: The jQuery bind() method are used to attache an event handler to elements.

203) How to use scrolling an ASP.NET Multiline Textbox using jQuery?
Answer: The jQuery code will be inside the <script></script> tag and always remained between head section or body section.

204) What is jQuery Datepicker in jQuery?
Answer: jQuery UI Datepicker is a highly configurable plugin which adds datepicker functionality to pages. The date format and language, restrict the selectable date ranges and add in buttons and other navigation options can easily be customised.

205) What is the $(window).load in jQuery?
Answer: $(window).load is an event which can fire when the DOM and all the content on the page is fully loaded.

206) In JQuery what do you understand by grouping?
Answer: If more than one selectors use the same declaration then they can be grouped together and are separated by a comma. In this way, CSS size can be reduced and can be made readable.

207) What is Semantic HTML?
Answer: Semantic HTML is a style of coding and in which tags embody what text is meant to convey. Some of the syntax for tags may be different than usual HTML syntaxes in semantic HTML .

208) Which one is faster, document.getElementByID(‘txtName’) or $(‘#txtName’).?
Answer: “$(‘#txtName’)” will internally makes a call to document.getElementByID(‘txtName’) to select txtName in jQuery method .  jQuery Will be written on top of JavaScript and it internally uses JavaScript, so JavaScript is always fast.

209) Explain width() vs css(‘width’)?
Answer: There are following ways to change the width of an element.

  1. .css(‘width’)
    $(‘#mydiv’).css(‘width’,’300px’);
    2. .width()
    $(‘#mydiv’).width(100);

210) What is .siblings() method in jQuery?
Answer:  To fetch siblings of every elements in the set of matched elements, siblings() method can be used. We filter the elements fetched by an optional selector.

.siblings([selector])
“selector” is the selector expression which specify the matched elements.

211) How is the deferred method in jquery important in relation to animate method?
Answer:  If the user wants to use the animation methods on a data which resides on the server and wants to handle at a single go, the user can make used of the .deferred method.

212) Explain the use of the .pushStack() method?
Answer: The pushStack() method can work by accepting an array of DOM elements and pushes them into a stack. By doing that call to methods like .end() and .andSelf are behave correctly. This method is internally used by jquery to keep track of all the previous collections of jquery while using a chain traversing method.

213) In jQuery, the method we use to check whether an element is empty or not is..?
Answer: Following method is used to check whether an element is empty or not
a. Using “:empt” selector

b. $.trim()

214) Explain what the following code will do?

$( “div#first, div.first, ol#items > [name$=’first’]” )

Answer:   It performs a query to retrieve any <div> element with the id first, and all <div> elements with the class first, along with all elements which are children of the <ol id=”items”> element and whose name attribute ends with the string “first”. It is an example of using multiple selectors at at a single steps.

215) The code below is for an application that requires defining a click handler for all buttons on the page, including those buttons that may be added later dynamically. What is wrong with this code, and how can it be fixed to work properly even with buttons that are added later dynamically?

// define the click handler for all buttons

$( “button” ).bind( “click”, function() {

alert( “Button Clicked!” )

});

 

/* … some time later … */

 

// dynamically add another button to the page

$( “html” ).append( “<button>Click Alert!</button>” );

Answer: The button which is added dynamically after the call to bind() would not have the click handler attached because the bind() method only attaches handlers to elements which exist at the time the call to bind() is made.
It is solved with functions  “event bubbling” to match events on both current and future elements.
This was done by replacing bind() with live() but live() was deprecated in jQuery 1.7. . delegate() works same as  live() but also provides control over how far an event must bubble up the DOM.

The recommended method is to use on(), that can behave like bind(), live(), or delegate() depending on syntax.
Following is the code

// define the click handler for all buttons

$( document ).on( “click”, “button”, function() {

alert( “Button Clicked!” )

});

 

/* … some time later … */

 

// dynamically add another button to the page

$( “html” ).append( “<button>Click Alert!</button>” );

216) Given the following HTML:

<div id=”expander”></div>

and the following CSS:

 

 

 

 

 

div#expander{

width: 100px;

height: 100px;

background-color: blue;

}

Answer: Write code in jQuery to animate the #expander div, expanding it from 100 x 100 pixels to 200 x 200 pixels over the course of three seconds.

Following is the code

$( “#expander” ).animate(

{

width: “200px”, // new width

height: “200px”, // new height

},

3000 ); // timeframe

217) What does the following code do?
Answer: $( “div” ).css( “width”, “300px” ).add( “p” ).css( “background-color”, “blue” );

It can select all the <div> elements and changes their CSS width to 300px. Then it can add all the <p> elements to the current selection, thereby it can finally change the CSS background color for both the <div> and <p> elements to blue.

218) Which of the two lines of code below is more efficient? Explain your answer?

document.getElementById( “logo” );

or

$( “#logo” );

Answer: The first line of code is more efficient and faster which is pure JavaScript without jQuery. The second line of code will trigger a call to the JavaScript version which is jQuery.

jQuery is built to make DOM manipulation easier at the cost of some performance overhead. Therefore jQuery is not always better choice than plain old JavaScript.

219) Create a plugin that would add and remove a class on hover.
Answer: The code to create a plugin which would add and remove a class on hover will be as below:

(function($)

{

$.fn.hoverClass = function(c)

{

return this.hover(

function() { $(this).toggleClass(c); }

);

};

})(jQuery);

 

// using the plugin

$(‘li’).hoverClass(‘hover’);

220) Write a code for the implementation of a module pattern.
Answer: The module pattern will allow the user to offer privacy to functions and variables. Following is the code for the implementation of a module pattern.

var feature =(function()

{

var privateThing = ‘secret’,

publicThing = ‘not secret’,

changePrivateThing = function()

{

privateThing = ‘super secret’;

},

sayPrivateThing = function()

{

console.log(privateThing);

changePrivateThing();

};

return

{

publicThing : publicThing,

sayPrivateThing : sayPrivateThing

}

})();

feature.publicThing; // ‘not secret’

feature.sayPrivateThing();

221) How do you attach a event to element which should be executed only once?
Answer: Using jQuery one() method attaches a handler to an event for the element which is executed at most once per element.
Following is the code

$(document).ready(function() {

$(“#btnDummy”).one(“click”, function() {

alert(“This will be displayed only once.”);

});

});

222) What are the disadvantages of Ajax?
Answer: Following are the disadvantages of Ajax.

1.Ajax will not support, if there is some Javascript problem with the browser or in the OS because AJAX is dependent on Javascript.
2.Ajax are problematic in Search engines because it uses Javascript for most of its parts.
3.Source code written in AJAX is human readable therefore there can be some security issues in Ajax.
4 Debugging is almost impossible to perform.
5.It has very slow and unreliable network connection.
6.It has some problem with browser back button when using AJAX enabled pages.

223) What are the technologies used by Ajax?
Answer: AJAX uses below technologies

  1. JavaScript
  2. XMLHttpRequest
  3. Document Object Model (DOM)
  4. Extensible HTML (XHTML)
  5. Cascading Style Sheets (CSS)

224) What Is the Format of an AJAX Request?
Answer: An AJAX request is written in any of the following formats:

  1. Text File
  2. HTML
  3. JSON object

225) How can you find out that an AJAX request has been completed?
Answer: The ReadyState property is used to check whether AJAX request has been completed.  The readyState property should be equal to four, it means the request has been completed and data is available.

226) What is JSON in Ajax?
Answer: JSON stands for as JavaScript Object Notation which is a safe and reliable data interchange format in JavaScript. It is easy to understand for both users and machines.

227) How many types of triggers are present in update panel?
Answer: There are following types of triggers which are used in update panel:

  1. PostBackTrigger will work as full postback and it cannot work asynchronously
  2. 2. AsyncPostBackTrigger are Partial post back asynchronously.

228) Which two methods are used for handling Cross-Domain Ajax Calls?
Answer: Following methods are used for handling Cross-Domain Ajax Calls

1.Cross-Origin Resource Sharing (CORS) will Work with all HTTP verbs and Mos modern web browsers and it also provides better support for error handling than JSONP.
2.JSON with padding (JSONP) can only work HTTP GET verb and on legacy browsers.

229) When should AJAX not be used?
Answer: In following cases AJAX should be used

1.AJAX should not be appropriate to use when the results can be determined by the client.
2.AJAX should not be appropriate to use when the magnitude of the response is such which it would be easier, and clear to redisplay the page.

230) How can AJAX response set a cookie?
Answer: AJAX response set a cookie in following ways

1. Make another ajax call with request where we can set the cookie, after getting response.
2.Make the cookie in Server, before sending the ajax response.

setcookie function can be use to set the cookie as below:

$cookieValue=’This is cookie value’;

setcookie(‘name’, $cookieValue, time() + 3600);

231) How can we send data in an Ajax call?
Answer: Following is the code to send data in an AJAX call

$.ajax({

url: ‘/my/site/url’,

data: { name: “Arun”, location: “Chandigarh” },

type: ‘post’,

success: function(result) {

console.log(result);

}

232) How to submit entire form data with Ajax?
Answer: Following is code to submit entire form data with AJAX:
var formData = $(‘form#formId’).serialize();

$.ajax({

url: ‘/my/site’,

data: formData,

type: ‘post’,

success: function(result) {

console.log(result);

}

});

233) How to URLencode a string before sending in Ajax?
Answer: Following is code to URLencode  string in AJAX

$.ajax({

url: ‘/ajax/url’,

dataType: “json”,

data: name=encodeURIComponent(‘Test’),

success: function(response) {

if(response.success == 1){

offWords = response.data;

}

},

error: function(xhr, ajaxOptions, thrownError) {

}

});

234) Do AJAX requests retain PHP Session info, when calling multiple times?
Answer: Yes, PHP session info can be retained over multiple ajax call. The duration of the php session are dependent on SESSION configuration.

235) How to update the image source, if the original image fails to load?
Answer: onError attribute are used to update the image path, when it is failed to load.

<img alt=”Image not found” onerror=”this.src=’show_img_when_

236) How can we send ajax request to another domain using JSONP?
Answer: JSONP (JSON with Padding) is way for overcoming XMLHttpRequest domain policy. Using JSONP the request can be sent to another domain.   Another domain URL with a parameter are included in JSONP.
Following is the code.

<script>

function myCalllbackFunction(data){

console.log(data);

}

</script>

<script src=”https://twitter.com/status/user_timeline/padr”>

237) How does jQuery store data related to an element?
Answer: Code for storing and retrieving data related to an element:
$(‘#myDiv’).data(‘keyName’, { foo : ‘bar’ });

$(‘#myDiv’).data(‘keyName’); // { foo : ‘bar’ }

Jquery will allow the user to store any kind of information on an element.

The $.fn.data is mostly used to store data related to an element.

Example of storing of relationship between elements with the use of $.fn. data.

$(‘#myList li’).each(function()

{

var $li = $(this), $div = $li.find(‘div.content’);

$li.data(‘contentDiv’, $div);

});

// later, the user is not required to look for the div again;

// the data can simply be read from the list items data;

var $firstLi = $(‘#myList li:first’);

$firstLi.data(‘contentDiv’).html(‘new content’);

238) What is the proper way in jQuery to remove an element from the DOM before its Promise is resolved?
Answer: The .remove() method will remove the element’s data along with the element itself, which will prevent any of the element’s unresolved Promises from resolving.

Therefore, use .detach() instead and follow with .removeData() after resolution, when it is necessary to remove an element from the DOM before its Promise is resolved.

239) What are the guidelines for an application to follow the principles of progressive enhancement?
Answer: Progressive enhancement is web development technique Which will allow the application to be accessible to any computer with any Internet connection.
Following are the guideline:
1.  any type of Internet connections basic content must be available to all browsers.
2. The basic functionalities of an application should  work in all browsers.

  1. The application should not override any of the user specified browser settings.
  2. The css files will linked externally to control the look and feel of the page.
  3. The javascripts can also be externally linked because it can enhance the user experience.

240) How to handle Controls attribute Using jQuery?
Answer:  .addClass(), .removeClass(), .css(), .toggleClass(), are used to handle Controls attribute using jQuery.

241) What is slice() method in jQuery?
Answer: This method will select a subset of the matched elements by giving a range of indices means it provides the set of DOM elements on the basis of it’s parameter (start, end).

Syntax: .slice( start, end[Optional] )
Start: specifies from where to start to select the elements.
End: specifies the range of the selection and indicates where to stop the selection of elements, excluding end element.

242) What is the difference between Map and Grep function in jQuery?
Answer: In $.map() it is required  to loop over each element in an array and modify its value where  the $.Grep() method will return the filtered array using some filter condition from an existing array.
$.map ( array, callback(elementOfArray, indexInArray))

243) How to disable jQuery animation?
Answer: If “jQuery.fx.off“, set to true, it disables all the jQuery animation. After this all animation methods are immediately set elements to their final state when called, and not display an effect.

244) How To Show The Alert Message On Button Click In Jquery?
Answer:  Alert message on Button Click can be handled by “OnClick” of the button in jquery.
Code:
<input type=”button” id=”myButton” onclick=”alert(‘Hi’)” />

245) How We Can Check Element Exists Or Not In Jquery?
Answer: Following is the code:

$(document).ready(function(){

if ($(‘# mycontrolid’).length > 0){

//Code Here if element exists.

});

});

246) How We Can Check/uncheck Radio Buttons In Jquery?
Answer: Following is the code to check/uncheck radio buttons:

// Check #mycontrolid

$(‘#mycontrolid’).attr(‘checked’, true);

// Uncheck #mycontrolid

$(‘#mycontrolid’).attr(‘checked’, false);

247) What Is The Use Of Validation Jquery Plugins?
Answer: The use of validation jquery plugins
$(‘#MyControlId’).rules(“add”, {

required: true

});

248) Which Method To Be Used To Stop The Animation?
Answer: We use the method called – “stop()” to stop the animation in jquery.

249) Can You Give An Example For Chaining Along With Code Snippet?
Answer: Following is the  code snippet:

Old Code:

$(document).ready(function(){

$(‘#MyControlID’).addClass(‘test’);

$(‘#MyControlID’).css(‘color’, ‘yellow’);

$(‘#MyControlID’).fadeIn(‘fast’);

});

New Code after chaining:

$(document).ready(function(){

$(‘#MyControlID’).addClass(‘test’)

.css(‘color’, ‘yellow’)

.fadeIn(‘fast’);

});

250) Explain Caching In Jquery?
Answer: Caching is temporary memory to store the data to increases the performance of the application. JQuery also has the similar concept.
old code

$(‘#MyControlID’).addClass(‘test’);
$(‘#MyControlID’).css(‘color’, ‘yellow’);
New Code for caching:

var $mycontrol = $(“#MyControlID”).css(“color”, “red”);
//Do somre stuffs here
$mycontrol.text(“Error occurred!”);

251) How We Can Write Code Specific To Browser In Jquery?
Answer: Yes, we can write code specific to browser using  “Jquery.Browser.”

252) How To Disable Elements Using “attr” In Jquery?
Answer: Following is the code
 $(‘#myControlID’).attr(‘disabled’,true);
$(‘#myControlID’).attr(‘disabled’, false);

253) How To Check/uncheck Radio Button Using Attr In Jquery?
Answer: Following is the code to check/uncheck radio button using Attr in Jquery
$(‘#myControlID’).attr(‘checked’,true);
$(‘#myControlID’).attr(‘checked’, false);

254) Why To Use “siblings” Method? Give Sample Code To Demonstrate The Same?
Answer:  “sibling” method is used on parent element to get the  the list of sibling elements.
Example
<ul><li> itemA </li><li id=”mycontrolID”> itemB </li><li class=”mycontrolclass”> itemC </li><li class=”mycontrolclass”> itemD </li></ul>$(‘li#mycontrolID’).siblings().css(‘color’,’yellow’);

255) Why To Use Jquery Dialog?
Answer: Jquery Dialog can be used as pop up. We can render the cshtml contents in Jquery Dialogue , if Jquery used in MVC .

256) How Can We Select Elements In Two Different Classes In Jquery?
Answer: Below is the sample code to select elements in two different classes in Jquery:
$(“.MyClass1.MyClass2”).css(‘color’,’green’);

257) How To Select All The <span> Elements Which Has Text ‘Learn’?
Answer:  We can select all <span> elements using below code –$(“span:contains(‘Learn’ )”)

258) How We Can Select The Specified <li> Element From The List Of <li> Elements In <ul>?
Answer: If we want to get the 3rd <li> from the list of elements in <ul> then We can write code as below –

$(“ul li:eq(2)”) // Index will start from 0.

259) In <table> Design Change The Color Of Even <tr> Elements To “White” And Change The Color Of Odd <tr> Elements To “red” Color? Give An Example Code?
Answer: Below is the sample code snippet :

$(“tr:even”).css(‘color’,’White’)
$(“tr:odd”).css(‘color’,’Red’)

260) Write A Code Snippet To Select <li> Elements Which Are In Index Greater Than 5 And Less Than 10 In Jquery?
Answer: Below is the code snippet :
$(“ul li:gt(5)”).css(‘color’,’green’)
$(“ul li:lt(10)”).css(‘color’,’blue’)

261) Write A Code Snippet To Select All <p> Elements Which Are In All Pages Except First Page?
Answer: Below is the code snippet :
$(“p :not(:first)”)

262) How To Select An Element With Id In Jquery?
Answer: To select an element with Id :
var divValue = $(”#sampleDivId”).val();

263) How To Select An Element With Class In Jquery?
Answer: To select an element with class :
$(“.sampleClass”).css(“border”,”2px solid blue”);

264) How To Use Length Function In Jquery To Text Existance Of An Element By Id?
Answer: We can use length method in jQuery to test if an element exists : $(”#mySampleDiv”).length )//Tests wheter the div with id mySampleDiv exists or not
$(mySampleDiv).find(”div”);

265) How will you select elements by class in jQuery?
Answer: We use the . sign followed by the class to select elements by class in jQuery

In the given example we are selecting all the elements having class ‘fruit’.
var elems = $(“.fruit”);

266) How will you select all the paragraphs inside a div having id ‘container’ using jQuery?
Answer: We  uses the following CSS selector div#container p.
var elems = $(‘div#container p’);

267) How will you select all the direct descendent paragraphs in a div having id ‘container’ using jQuery?
Answer: For this we will use the following CSS selector div#container > p.
var elems = $(‘div#container > p’);

jQuery is a light weight Java script library. jQuery is a very compact and easy to user Java script library, it provides lot of flexibility and ease to java developers to use apply java script code in light weight mode. jQuery is the most popularly used java script library by majority of the websites and web applications across the world. Due to its popularity and flexibility, jQuery has become an essential technical skill for any web  developer. Above listed 267 frequently asked jQuery interview questions will help you to crack your job interview easily.

Share this: