Wednesday, 27 November 2013

jQuery interview questions and answers

Q1. What is jQuery?

Ans: jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.

Q2. Why do we use jQuery?

Ans: Due to following advantages.
  • Easy to use and learn.
  • Easily expandable.
  • Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
  • Easy to use for DOM manipulation and traversal.
  • Large pool of built in methods.
  • AJAX Capabilities.
  • Methods for changing or applying CSS, creating animations.
  • Event detection and handling.
  • Tons of plug-ins for all kind of needs.

Q3. How JavaScript and jQuery are different?

Ans: JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

Q4. Difference between $(document).ready() and window.onload

Ans:- 

$(document).ready() :
  1. This event is triggered when dom is ready for interaction. It means that this event is called when value of document.readystate becomes as “interactive”.
    $(document).ready(function() {
        console.log("document state is "+document.readystate);
    });
    
    It will be logged as “document state is interactive”.
  2.  There can be multiple “ready” events but these events will be trigger in the same respect as they are being load in the DOM.
    <script>
    
       $(document).ready(function() {
           console.log("first handler");
       });
    
       $(document).ready(function() {
           console.log("second handler");
       });
    
    </script>
    
    First “first handler” and then “sencond handler” will be logged in console.
  3. This is a jquery event and use of this event is that there is no need to wait of loading all content in the dom for calling any functionality.
window.onload :
  1. This event is triggered when whole content is loaded in the dom. It means that this event is called when value of document.readystate becomes as“complete”.
    window.onload = function () {
        console.log("document state is "+document.readystate");
    };
    
    It will be logged as “document state is complete”.
  2.  There can not be multiple “onload” events. If there are multiple events then last loaded event in the dom will override all previous events..
    <script>
    
       window.onload = function () {
           console.log("first handler");
       };
    
       window.onload = function () {
          console.log("second handler");
       };
    
    </script>
    
    Only “sencond handler” will be logged in console.
  3. This is a native javascript event and this event does not get triggered until all assets such as images have been completely loaded in the dom.


Q4. What is 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 element. 



Selector     Example                Selects

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

Q5. Write the code for selecting the 1st div element, 4th div element, last div, and for                even and odd div elemets also. one by one?
apply the red color on the above 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");

Q6. What is Chaining in jQuery? 

In jQuery, Chaining means to connect multiple functions, events on selectors. look at Sample Code 1 and 2. 
Sample Code 1 

$(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 then 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. This is the advantage of Chaining. 

Q7.  If you have a table, how you will apply the two different colour on alternate rows using Jquery? 


<table border="1">



  <tr><td>Vikas Ahlawat</td></tr>



  <tr><td>Edwin George</td></tr>

  <tr><td>Rohit Khurana</td></tr>

  <tr><td>Gyan Singh</td></tr>

</table>



<script src="jquery.js"></script>



<script>



$(document) ready(function()



{

  $("tr:even") css("background-color", "#f4f4f8");

  $("tr:odd") css("background-color", "#ffffff");

});

</script>


Q8.  Name the Jquery method which is used to hide selected elements? 

.hide()

Q9. Can we use our own specific character in the place of $ sign in Jquery or What                                   is noConflict() method

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. Here is an example: 

var Rakesh = $.noConflict();
Rakesh (document) ready(function(){
  Rakesh ("button") click(function(){
    Rakesh ("p") text("jQuery is still working!");
  });
});

Q10. Name the 5 Jquery events? 

jQuery Events 

jQuery click() event. 
jQuery dblclick() event. 
jQuery mouseenter() event. 
jQuery mouseleave() event. 
jQuery mousedown() event. 
jQuery mouseup() event. 
jQuery hover() event. 
jQuery focus() and blur() events. 


Q11.  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.
Example:-
In this 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>Soda</li>
</ul>

Q12. How do you select element by ID in jQuery?

Ans: To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select element with ID "txtName", then syntax would be,

$('#txtName')


Q13. What are the fastest selectors in jQuery?

Ans: ID and element selectors are the fastest selectors in jQuery.

Q14. What are the slow selectors in jQuery?

Ans: class selectors are the slow compare to ID and element.

Q15. Which is fast document.getElementByID('txtName') or $('#txtName').?

Ans: Native JavaScipt is always fast. jQuery method to select txtName "$('#txtName')" will internally makes a call to document.getElementByID('txtName'). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

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

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

And the second way is using the "$.trim()" method.

$(document).ready(function(){
    if($.trim($('#element').html())=='') {
       //Element is empty
  }
});  
Q17. 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.

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

Q18. 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 thesize() method as jQuery provide .length property and which does the same thing. But the .lengthproperty is preferred because it does not have the overhead of a function call. 


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


Q20. How to find an element Starting and Ending with certain text using Jquery? 
         For example:
         <div id="AAxxxxZZ"> AAxxxxZZ </div>          <div id="BxxxxU"> BxxxxU </div>          <div id="CxxxxY"> CxxxxY </div>
       if I need to find an element with id that starts with AA and end with ZZ. (Dell Interview Question)
Ans :- $('div[id^="AA"][id$="ZZ"]')





No comments:

Post a Comment