JQUERY Interview Questions and Answers

jQuery is the lightweight, write less and do more JavaScript library.The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation..


21) What does $("div") will select?

This will select all the div elements on page.


22) How to select element having a particular class (".selected")?

$('.selected'). This selector is known as class selector. We need to prefix the class name with "." (dot).


23) What does $("div.parent") will select?

All the div element with parent class.


24) What are the fastest selectors in jQuery?

 ID and element selectors are the fastest selectors in jQuery.


25) What are the slow selectors in jQuery?

class selectors are the slow compare to ID and element.


26) How jQuery selectors are 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".

Syntax:

$("p#elmID .myCssClass");


27) Which is fast document.getElementByID('id') or $('#id')?

Native JavaScipt is always fast. jQuery method to select txtName $('#id')will internally makes a call to

document.getElementByID('id').

As jQuery is written on top of JavaScript and it internally uses JavaScript only,

So JavaScript is always fast.


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

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

In below example, this is an object but since it is not wrapped in $(), we can't use jQuery method and use the native JavaScript to get the value of span element.

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


29) How do you check if an element is empty?

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


30) What is the use of jquery .each() function?

 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.

Syntax:

$.each(data,function(key,value){

console.log(key); //Key

console.log(value);  //Value

});