jQuery important questions

1). What is jQuery?

jQuery is JavaScript library which required a jquery.js file. After that you can write the jQuery as fallows. It uses “$” as the shorthand to write jquery

Syntax

$(document).ready(function()
{
//function body
});

2). When was jQuery founded and by whom?

It was released in January 2006 at BarCamp NYC by John Resig (jQuery founder). Check jQuery History in detail.

3). What scripting language is jQuery written in?

Ans: JavaScript

4). Write a basic code for add jQuery library to pages?

Below is sample code for the same:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// You can write the code here
</script>
</head>
<body>
<a href="http://www.codeconfig.in/">Jquery Interview Questions and
Answers</a>
</body>
</html>

5). What are jQuery Selectors? Give some examples?

Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the elements.

* $("*");               //All elements
#id$("#lastname");      //The element with id=lastname
.class$(".intro");      // All elements with class="intro"
element$("p");          //All p elements

6). What $(“div.Mycode”) will select?

It will select all the div elements with Mycode class.

7). jQuery uses CSS selectors and XPath expressions to select elements. Is this true or false.

It is true.

8). What are the fastest selectors in jQuery?

 ID and element selectors are the fastest selectors in jQuery.

9). What are the slower selectors in jQuery?

Class selectors are slower in jQuery.

10). Which one is faster jQuery ID selector or JavaScript getElementById()?

JavaScript getElementById() is faster than jQuery Id ($(“#elementID”)) selector.

11). Where jQuery code executes? On client browser or server browser?

On client browser.

12). Write the code for selecting the 1st div element, 4th div element, last div, and for even and odd div elements also with one-by-one examples, also apply red color on DIV?

<div class="questions">
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
<div class="box"> Question</div>
</div>

Code for first div: $("div.questions > div:first").css("color","red");

Code for 4th div: $("div.questions > div:nth-child(4)").css("color", "red");

Code for last div: $("div.questions > div:last").css("color","red");

Code for even div: $("div.questions > div:even").css("color","red");

Code for odd div: $("div.questions > div:odd").css("color","red");

13). Write the code for select second last div element?

Code for second last div : $("div.questions > div::nth-last-child(2)").css("color", "red"); 

<!-- It was Introduced in CSS3 -->

14). What are the advantages of using jQuery over JavaScript in ASP.NET web application?

Below are the advantages of using jQuery over JavaScript

  1. jQuery is well written optimized JavaScript code so; it will be faster in execution unless we write same standard optimized JavaScript code.
  2. jQuery is concise java script code, means minimal amount of code is to be written for the same functionality than the JavaScript.
  3. JavaScript related Development is fast using jQuery because most of the functionality is already written in the library, and we just need to use that.
  4. jQuery has cross browser support, so we save time for supporting all the browsers.

15). What is Chaining in jQuery?

In jQuery, Chaining means to connect multiple functions, events on selectors. look at Sample Codes.

Sample Code without Chaining

$(document).ready(function(){
$('#dvContent').addClass('dummy');
$('#dvContent').css('color', 'red');
$('#dvContent').fadeIn('slow');
});

Sample Code 2 using chaining.

$(document).ready(function(){
$('#dvContent').addClass('dummy')
.css('color', 'red')
.fadeIn('slow');
});

Both the sample codes above will perform the exact same thing, but the only difference is that Sample code 2 is using Chaining. But Code 2 is faster and shorter than Code 1. The problem with the Sample Code 1 is that for every statement, jQuery has to search the entire DOM and find the element and after that executes the attached function on it. But when chaining is used, then jQuery has to find the element only once and it will execute all the attached functions one by one.

16). Is jQuery a library for client scripting or server scripting?

It is Client Script.

17). What are features of jQuery?

  1. One can easily provide effects and can-do animations.
  2. Applying / Changing CSS.
  3. Cool plugins.
  4. Ajax support.
  5. DOM selection events.
  6. Event Handling.

18). How to check jQuery UI loaded or not?

Using below code we can check if jQuery UI is loaded or not.

if($.ui)
{
  // jQuery UI is loaded
}
else 
{
  // jQuery UI is not loaded
}

19). How to check currently loaded jQuery UI version on web page?

Using below code we can get version:

$.ui.version

20). Write the code for setting datetimepicker on textbox click.

If below is our textbox

<input type="text" id="txtDOB" name="DOB" value="Select Date" />

then jQuery code for datetimepicker will be

$("#txtDOB").datepicker();

21). If you have a table, how you will apply the two different colors on alternate rows using jQuery?

Please check below code for applying colors to alternate row of table

<table border="1">
<tr><td>Rakesh Kumar</td></tr>
<tr><td>Mukesh Mankotia</td></tr>
<tr><td>Rajesh Thakur</td></tr>
<tr><td>Amit Srivastava</td></tr>
</table>


<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"> </script>

<script>
$(document).ready(function()
{
  $("tr:even").css("background-color", "#f4f4f8");
  $("tr:odd").css("background-color", "#ffffff");
});
</script>

22). Name the jQuery method which is used to hide selected elements?

.hide() is jQuery method used to hide selected elements.

$("#Id1").hide();)

23). Name the jQuery methods which are used for applying CSS class?

$("#Id1").addClass('YourClassName');       // for applying class

$("#Id1").removeClass('YourClassName');    // for removing CSS class

24). What is the use of attr() method in jQuery?

The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of theof the first matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

$(selector).attr(attribute)           //it will return the value of an attribute.
$(selector).attr(attribute,value)      //it will set the value of an attribute.

$(selector).attr({attribute:value, attribute:value,...})      //for set multiple attribute.

25). Can we use both jQuery and AJAX together?

Yes, we can use.

26). What is the name of jQuery method which is used to perform an asynchronous HTTP request?

 jQuery.ajax()

27). What is the use of jQuery load() method?

The jQuery load() method is a powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element without reload the complete page.

Example: The following example loads the content of the file “demo_test.txt” into a specific <div> element.

$("#div1").load("demo_test.txt");

28). Can we use our own specific character in the place of $ sign in jQuery?

Yes, you can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use. Below is an example:

var rakesh = $.noConflict();
rakesh(document).ready(function()
{
   rakesh("button").click(function()
   {
    rakesh("p").text("jQuery is still working with text rakesh instead of $ ");
   });
});

29). Name few jQuery events?

  1. jQuery Events
  2. jQuery click() event.
  3. jQuery dblclick() event.
  4. jQuery mouseenter() event.
  5. jQuery mouseleave() event.
  6. jQuery mousedown() event.
  7. jQuery mouseup() event.
  8. jQuery hover() event.
  9. jQuery focus() event
  10. jQuery blur() events.

30). What is difference between jQuery’s ‘ready’ and ‘holdReady’?

jQuery’s ready is an event which gets triggered automatically when DOM is ready while ‘holdReady’ is a signal/flag to hold this triggering. ‘holdReady’ was included in 1.6 version and it works only if used before the execution/triggering of ready event. Once ready event is fired, it has nothing to do. It is useful in dynamically loading scripts before the ready starts. It releases ready event execution when used with a true parameter.

31). What is the use jQuery $.ajax() method?

The jQuery ajax() method is used to perform an AJAX (asynchronous HTTP) Request.

32). Name any four parameters of jQuery ajax method?

  1. url : Specifies the URL to send the request to. Default is the current page
  2. type : Specifies the type of request. (GET or POST)
  3. data : Specifies data to be sent to the server
  4. cache: A Boolean value indicating whether the browser should cache the requested pages. Default it is true.
  5. beforeSend(xhr): A function to run before the request is sent.

33). When can we use jQuery?

jQuery can be used to perform the followings:

  1. Call methods on specific events
  2. Traverse the documents
  3. For apply CSS
  4. Manipulation purpose and
  5. To add effects too.
  6. For apply animations
  7. For give attractive look (dialogbox etc.)
  8. For asynchronous calls ($.ajax())

34). How to select combo box selected value and text using jQuery?

var StateID = $("#StateCbx").val();                      // Or you can use it
$("#iStateID").val();

var StateName = $("#StateCbx option:selected").text();
alert("Selected combobox text is= " + StateName + " and value is= " + StateID);

35). jQuery html() method works for both HTML and XML documents?

No, it only works for HTML.

36). Can you call C# code behind method using jQuery?

Yes, we can do so by using $.ajax method.

37). What is the use of jQuery.data()?

jQuery’s data method gives us the ability to associate arbitrary data with DOM nodes and JavaScript objects. This makes our code more concise and cleaner.

38). Is jQuery a W3C standard?

No.

39). What is the use of jQuery .each() function?

Basically, the jQuery .each() function is used to loop through each element of the target jQuery object. Very useful for multi element DOM manipulation, looping arrays and object properties. In below example alert box will open 3 times because DOM contain 3 <li> tags.

<script>
$(document).ready(function(){
  $("button").click(function(){
    $("li").each(function(){
      alert($(this).text())
    });
  });
});
</script>

<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
</ul>

40). If you have a server control (asp.net server control, Button) and on the click of button you want to call a jQuery function, so how you will call a jQuery function without postback?

ASP.NET provides the OnClientClick property to handle button clicks. You can use this property on Button, LinkButton and ImageButton. The same OnClientClick property also allows you to cancel a postback. So, I can use OnClientClick property and jQuery function will return false.

<script type="text/javascript">
    function callRakesh()
    {
    alert('Hello Rakesh');
        return false;
    }
</script>

<asp:Button ID="Button1" runat="server" OnClientClick="return callRakesh();" Text="Button" />

41). What is the use of .Size() method in jQuery?

jQuery’s .size() method returns number of elements in the object. This means that you can count the number of elements within an object using this function.

42). What is the difference between jquery.size() and jquery.length?

jquery.size() and jquery.length both returns the number of elements found in the object. But jquery.length is faster than jquery.size() because size() is a method, but length is a property.

43). How you can debug jQuery code/What are the technique to debug jQuery?

Add the keyword “debugger;” to the line from where we want to start the debugging and then run the Visual Studio in Debug mode by pressing F5 or using the Debug button.

44). Difference between jQuery-x.x.x.js and jQuery.x.x.x min.js?

  1. jQuery-x.x.x.js = Pretty and easy to read. Check HERE all versions.
  2. jQuery.x.x.x min.js = It is compressed and non-readable. But has a smaller file size. Put this one on your site for fast loading because of less size. Usually, it is used in production environments whereas above is used in development environments.

45). How to get the server response from an AJAX request using jQuery?

When invoking functions that have asynchronous behavior, we must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received. Below an example of making an AJAX call and alerting the response (or error):

$.ajax({
url: 'home/user',
success: function(response) {
alert(response);
},
error: function(xhr) {
alert('Error! Status = ' + xhr.status);
}
});

46). Do we need to add the jQuery file both at the Master Page/_layout and Content page as well?

No, if the jQuery file has been added to the master page or _layout, then we can access the content page directly without adding any reference to it. This can be done using this simple example as show below.

<script type="text/javascript" src="jQuery-X.X.X-min.js"></script>

47). Difference between ‘onload()’ and ‘document.ready()’ function used in jQuery?

We can add more than one document.ready() function in a page, but we can have only one onload() function on one page.

Document.ready()‘ function is called as soon as DOM is loaded. ‘body.onload()‘ function is called when everything (DOM and images) gets loaded on the page.

48). Is it possible to use other client-side libraries like MooTools, Prototype along with jQuery?

Yes, you can use jquery.noConflict to avoid the conflict while using these libraries.

49). What is a CDN?

A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance.

50). Which is the popular jQuery CDN? List down the advantages of using CDN?

Below are popular jQuery CDNs.

  1.  Google.
  2.  jQuery.    
  3.  Microsoft

Advantages of CDN:

  1. Light weighted (minified files) therefore download faster on client side form these side.
  2. Reduced the load on the server.
  3. Most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js"> </script>

<script type="text/javascript" src="http://code.jquery.com/jquery-x.x.x.min.js"> </script>

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-x.x.x.min.js"> </script>

Suggestions:

It’s always better to load the Js library from CDN, because of the above   given benefits, if in some case it fails (it will never happen; only very little chances are there) then pick from local folder.

Example is like:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js">
</script> 
<script type="text/javascript">
if(typeof jQuery == 'undefined') 
{ 
 document.write(unescape("%3Cscript src='Scripts/jquery.x.x.x.min.js' type='text/javascript'%3E%3C/script%3E")); 
} 
</script>

51). How are jQuery selectors executed?

Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class “.myCssClass” and after that it will reject all the other elements which are not in “p#elmID”.

$("p#elmID .myCssClass");

52). Which is fast document.getElementByID(‘txtUserName’) or $(‘#txtUserName’)?

Native JavaScript is always fast. jQuery method to select txtUserName “$(‘#txtUserName’)” will internally makes a call to document.getElementByID(‘txtUserName’). As jQuery is written on top of JavaScript and it internally uses JavaScript only, So JavaScript is always fast.

53). Difference between $(this) and ‘this’ in jQuery?

this and $(this) refers to the same element. The only difference is the way they are used. ‘this’ is used in traditional sense, when ‘this’ is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.

Check below examples:

$(document).ready(function(){ $('#spnValue').mouseover(function(){ alert($(this).text()); }); });

//And

$(document).ready(function(){ $('#spnValue').mouseover(function(){ alert(this.innerText); }); })

54). How do you check if an element is empty?

We can check element for empty as below:

$(document).ready(function(){ if ($('#element').is(':empty')){ //Element is empty }); });

55). How do you check if an element exists or not in jQuery?

Using jQuery length property, we can ensure whether element exists or not.

$(document).ready(function(){ 
if ($('#element').length > 0)
{ 
//Element exists 
}
);
});

56). What is the difference between $(‘div’) and $(‘<div/>’) in jQuery?

$(‘<div/>’) : This creates a new div element. However, this is not added to DOM tree unless you don’t append it to any DOM element.

$(‘div’) : This selects all the div element present on the page.

Check More on jQuery:

Leave a Reply

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