Jquery Interview Questions 2013-1 - DOTNET

Jquery Interview Questions 2013-1

Q31. How do you check if an element is empty?
Ans: There are 2 ways to check if element is empty or not. We can check using ":empty" selector.
1
$(document).ready(function(){
2
    if ($('#element').is(':empty')){
3
       //Element is empty
4
  }
5
});
And the second way is using the "$.trim()" method.
1
$(document).ready(function(){
2
     if($.trim($('#element').html())=='') {
3
       //Element is empty
4
  }
5
});
Q32. How do you check if an element exists or not in jQuery?
Ans: Using jQuery length property, we can ensure whether element exists or not.
1
$(document).ready(function(){
2
    if ($('#element').length > 0){
3
       //Element exists
4
  });
5
});
Q33. What is the use of jquery .each() function?
Ans: The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.
Q34. What is the difference between jquery.size() and jquery.length?
Ans: jQuery .size() method returns number of element in the object. But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call. 
Q35. What is the difference between $('div') and $('<div/>') in jQuery?
Ans: $('<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.
Q36. What is the difference between parent() and parents() methods in jQuery?
Ans: The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.
Q37. What is the difference between eq() and get() methods in jQuery?
Ans: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used. Find out more 
here.
Q38. How do you implement animation functionality?
Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:
1
(selector).animate({styles},speed,easing,callback)
·                     styles: Specifies one or more CSS properties/values to animate.
·                     duration: Optional. Specifies the speed of the animation.
·                     easing: Optional. Specifies the speed of the element in different points of the animation. Default value is "swing".
·                     callback: Optional. A function to be executed after the animation completes.
Simple use of animate function is,
1
$("btnClick").click(function(){
2
  $("#dvBox").animate({height:"100px"});
3
});
Q39. How to disable jQuery animation?
Ans: Using jQuery property "jQuery.fx.off", which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.
Q40. How do you stop the currently-running animation?
Ans: Using jQuery ".stop()" method.
Q41. What is the difference between .empty(), .remove() and .detach() methods in jQuery?
Ans: All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

.empty(): This method removes all the child element of the matched element where remove() method removes set of matched elements from DOM.

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. 

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

Find out more 
here
Q42. Explain .bind() vs .live() vs .delegate() vs .on()
Ans: All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.

.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn't work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection.

.live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method.

.delegate(): The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored and it also supports chaining.

.on(): Since live was deprecated with 1.7, so new method was introduced named ".on()". This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.

Find out more 
here
Q43. What is wrong with this code line "$('#myid.3').text('blah blah!!!');"
Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar"). 
So the correct syntax is,
1
$('#myid\\.3').text('blah blah!!!');

Q44. How to create clone of any object using jQuery?
Ans: jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
1
$(document).ready(function(){
2
  $('#btnClone').click(function(){
3
     $('#dvText').clone().appendTo('body');
4
     return false;
5
  });
6
});
Q45. Does events are also copied when you clone any element in jQuery?
Ans: As explained in previous question, using clone() method, we can create clone of any element but the default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.
1
$(document).ready(function(){
2
   $("#btnClone").bind('click', function(){
3
     $('#dvClickme').clone(true).appendTo('body');
4
  });
Q46. What is difference between prop and attr?
Ans: attr(): Get the value of an attribute for the first element in the set of matched elements. Whereas,.prop(): (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements. 

Attributes carry additional information about an HTML element and come in name="value" pairs. Where Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties. 

attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state. Find out more 
here.
Q47. What is event.PreventDefault?
Ans: The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.
Q48. What is the difference between event.PreventDefault and event.stopPropagation?
Ans: event.preventDefault(): Stops the default action of an element from happening. 
event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.
Q49. What is the difference between event.PreventDefault and "return false"?
Ans: e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.
Q50. What is the difference between event.stopPropagation and event.stopImmediatePropagation?
Ans: event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.
1
$("p").click(function(event){
2
  event.stopImmediatePropagation();
3
});
4
$("p").click(function(event){
5
  // This function won't be executed
6
  $(this).css("background-color", "#f00");
7
});
If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.
Q51. How to check if number is numeric while using jQuery 1.7+?
Ans: Using "isNumeric()" function which was introduced with jQuery 1.7. 
Q52. How to check data type of any variable in jQuery?
Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.
Q53. How do you attach a event to element which should be executed only once?
Ans: Using jQuery one() method. This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.
1
$(document).ready(function() {
2
    $("#btnDummy").one("click", function() {
3
        alert("This will be displayed only once.");
4
    });
5
});
Q54. Can you include multiple version of jQuery? If yes, then how they are executed?
Ans: Yes. Multiple versions of jQuery can be included in same page.
Q55. In what situation you would use multiple version of jQuery and how would you include them? 
Ans: Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page.

Below code shows how to include multiple version of jQuery.
1
<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>
2

3
<script type='text/javascript'>
4
 var $jq = jQuery.noConflict();
5
</script>
6

7
<script type='text/javascript' src='js/jquery_1.7.2.min.js'></script>
By this way, for your own jQuery code use "$jq", instead of "$" as "$jq" refers to jQuery 1.9.1, where "$" refers to 1.7.2.
Q56. Is it possible to hold or delay document.ready execution for sometime?
Ans: Yes, its possible. With Release of jQuery 1.6, a new method "jQuery.holdReady(hold)" was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced. 
1
2
$.holdReady(true);
3
$.getScript("myplugin.js", function() {
4
     $.holdReady(false);
5
});
Q57. What is chaining in jQuery?
Ans: Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on.
1
$(document).ready(function(){
2
    $('#dvContent').addClass('dummy');
3
    $('#dvContent').css('color', 'red');
4
    $('#dvContent').fadeIn('slow');
5
});
The above jQuery code sample can be re-written using chaining. See below.
1
$(document).ready(function(){
2
    $('#dvContent').addClass('dummy')
3
          .css('color', 'red')
4
          .fadeIn('slow');    
5
});
Not only functions or methods, chaining also works with events in jQuery.
Q58. How does caching helps and how to use caching in jQuery?
Ans: Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
1
$("#myID").css("color", "red");
2
//Doing some other stuff......
3
$("#myID").text("Error occurred!");
4
Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,
1
var $myElement = $("#myID").css("color", "red");
2
//Doing some other stuff......
3
$myElement.text("Error occurred!");
4
So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.
Q59. You get "jquery is not defined" or "$ is not defined" error. What could be the reason?
Ans: There could be many reasons for this.
·                     You have forgot to include the reference of jQuery library and trying to access jQuery.
·                     You have include the reference of the jQuery file, but it is after your jQuery code.
·                     The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.

Q60. How to write browser specific code using jQuery?
Ans: Using jQuery.browser property, we can write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9.
Copyright © 2015 DOTNET All Right Reserved