Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
All good things come in small packages and so does jQuery. It is a tiny JavaScript library used for web development and provides an entertaining experience of the web. jQuery is one of the most popular JavaScript libraries. jQuery Interview Questions will provide you with in-depth knowledge and help you prepare for your interviews.
JavaScript | jQuery |
It is a weakly typed, dynamic programming language | jQuery is a Concise and fast JavaScript library |
It is an interpreted language | It uses resources of JavaScript to make tasks simpler and easier |
You need to write your own script and it can be a time-consuming process | You only have to write existing JQuery scripts so it saves time |
Don’t need to add any additional plugins as all browsers support JavaScript | You may have to include jQuery library URL in the header of the page |
Too many lines of Code | Fewer lines of Code |
jQuery is an efficient & fast JavaScript Library created by John Resig in 2006. The motto of jQuery is – write less, do more. It is designed to simplify the client-side scripting of HTML. The main purpose of jQuery is to provide an easy way to use JavaScript on your website to make it more interactive and attractive.
It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
Some of the key features of jQuery are:
DOM manipulation− jQuery makes the selection of DOM elements easy, traverse them and modify their content by using cross-browser open source selector engine.
Event handling− It provides an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.
AJAX Support− jQuery helps you to develop a responsive and feature-rich website with AJAX technology.
Animations− This framework comes with plenty of built-in animation effects which you can use in your websites.
Lightweight − It is a very lightweight library – about 19KB in size.
Cross Browser Support− jQuery has cross-browser support and works well in IE 6.0+, Safari 3.0+, Chrome and Opera 9.0+.
There are many advantages of using jQuery. Some of them include :
It is like an enhanced version of JavaScript so there is no overhead in learning a new syntax.
jQuery has the ability to keep the code simple, readable, clear and reusable.
It has Cross-browser support.
This would remove the requirement for writing complex loops and DOM scripting library calls.
jQuery helps in event detection and handling.
It provides tons of plug-ins for all kind of needs.
A jQuery Selector is a function that uses the expressions to find out matching elements from a DOM based on the given criteria. In a simple language, selectors are used to select one or more HTML elements using jQuery. Once an element is selected then we can perform various operations on that selected element.
Selecting an element in DOM is done with the help of $() construct with a string parameter containing any CSS selector expression. $() will return zero or more DOM elements on which you can apply any effect or style.
There are three main types of selectors used in jQuery:
Selector | jQuery Syntax | Description |
Tag Name | $(‘div’) | All div tags in the document |
ID | $(‘#TextId’) | Selects element with ID as TextId. |
Class | $(‘.myclass’) | Selects all elements with class as myclass. |
jQuery no-conflict is an option given by jQuery to overcome the conflicts between the different javascript frameworks or libraries. When you use jQuery no-conflict mode, you replace the $ to a new variable and assign jQuery some other JavaScript libraries. Also, the $ is used as a function or variable name that jQuery has.
• .empty() – This method is used to remove all the child elements from matched elements.
Syntax-
$(selector).empty();
• .remove() – This method is used to remove all the matched element. It will remove all the jQuery data associated with the matched element.
Syntax-
$(selector).remove();
• .detach() – This method is same as .remove() method except that the .detach() method doesn’t remove jQuery data associated with the matched elements.
Syntax-
$(selector).detach();
jQuery provides amazing effects and you can apply them quickly with a simple configuration. The effect can be either hiding, showing, toggling, fadeout, fadein, fadeto and many more. Some other methods to provide effects include the following:
animate( params, [duration, easing, callback] ) This function makes custom animations for your HTML elements.
fadeIn( speed, [callback] ) This function fades in all the matched elements by adjusting their opacity and firing an optional callback after completion.
fadeOut( speed, [callback] ) This function is used to fade out all the matched elements by adjusting their opacity to 0, then setting the display to “none” and firing an optional callback after completion.
fadeTo( speed, opacity, callback ) This function fade the opacity of all the matched elements to a specified opacity and firing an optional callback after completion.
stop( [clearQueue, gotoEnd ]) This function stops all the currently running animations.
Ajax allows the user to exchange data with a server and update parts of a page without reloading the entire page. Some of the functions of ajax include:
$.ajax() – This is considered to be the most low level and basic of functions. It is used to send requests. This function can be performed without a selector.
$.ajaxSetup() – This function is used to define and set the options for various ajax calls.
$.getJSON() – This is a special type of shorthand function which is used to accept the url to which the requests are sent. Optional data and optional callback functions are also possible in such functions.
There are two different methods in jQuery to change the width of an element. The first way is to use .css(‘width’) and other way is to use .width().
For example-
$('#mydiv').css('width','300px'); $('#mydiv').width(100);
The difference in .css(‘width’) and .width() is the data type of value we specify or return from both the functions. In .css(‘width’) we have to add px in the width value while in .width() we don’t have to add px.
The bind() method does not attach events to those elements which are added after DOM is loaded. Whereas, live() and delegate() methods attach events to the future elements as well.
The difference between live() and delegate() methods is live() function does not work in chaining. It will work only on a selector or an element. But delegate() method works in chaining.
For example
$(document).ready(function(){ $("#myTable").find("tr").live("click",function(){ alert($(this).text()); }); });
The above code will not work using live() method. But we can accomplish this with delegate() method.
$(document).ready(function(){ $("#dvContainer")children("table").delegate("tr","click",function(){ alert($(this).text()); }); });
The param() method is used to represent an array or an object in a serialized manner. While making an ajax request we can use these serialize values in the query strings of URL.
Syntax:
$.param(object | array, boolValue)
“object | array” specifies an array or an object to be serialized.
“boolValue” specifies whether to use the traditional style of param serialization or not.
this and $(this) refer to the same element but the difference is that “this” is used in a traditional method but with $() it becomes a jQuery object on which we can use the functions of jQuery.
$(document).ready(function(){ $('#clickme').click(function(){ alert($(this).text()); alert(this.innerText); }); });
In the above example, when only “this” keyword is used then we can use the jQuery text() function to get the text of the element. Once the “this” keyword is written with $() then we can use the jQuery function text() to get the text of the element.
To deal with cookies in jQuery you have to use the Dough cookie plugin. Dough is easy to use and has some powerful features.
$.dough(“cookie_name”, “cookie_value”);
$.dough(“cookie_name”);
$.dough(“cookie_name”, “remove”);
A jQuery connect is a plugin used to connect or bind a function with another function. Connect is used to execute a function from any other function or plugin.
It can be used by downloading jQuery connect file from jQuery.com and then include that file in the HTML file. You have to use $.connect to connect one function to another.
jQuery .size() method gives the total number of element present in the object. But size() method is not preferred as jQuery has .length property. It does the same thing but the .length property does not have the overhead of a function call.
There are two ways to handle this issue:
For example:
$('#mydiv').click(function(e){ if( $(e.target).is('a') ) fn.call(e.target,e); }); $('#mydiv').load('my.html')
For example:
$('a').click(fn); $('#mydiv').load('my.html',function(){ $('#mydiv a').click(fn); });
$( "div#first, div.first, ol#items > [name$='first']" )
This code performs a query to retrieve any <div> element with the id first. It also includes all <div> elements with the class first and all elements which are children of the <ol id=”items”> element whose name attribute ends with the string “first”. This shows how to use multiple selectors at once. The function will return a jQuery object containing the results of the query.
$(window).load is an event that fires when the DOM and other contents on the page is fully loaded. This event is fired after the ready event.
In most cases, the script can be executed as soon as the DOM is fully loaded. The ready() is usually the best place to write your JavaScript code. But there could be some scenario where you might need to write scripts in the load() function. For example, to get the actual width and height of an image.
The $(window).load event is fired once the DOM and all the CSS, images and frames are fully loaded. So, it is the best place to write the jQuery code to get the actual image size or to get the details of anything that is loaded just before the load event is raised.
Content Delivery Network or Content Distribution Network(CDN) is a large distributed system of servers deployed in multiple data centers across the internet. It provides the files from servers at a higher bandwidth that leads to faster loading time. These are several companies that provide free public CDNs:
Microsoft
Yahoo
Advantages of using CDN:
It reduces the load from the server.
CDN also saves bandwidth. jQuery framework is loaded faster from these CDN.
If a user regularly visits a site which is using jQuery framework from any of these CDN, it will be cached.
jQuery library can be used in the ASP.Net project by downloading the latest jQuery library from jQuery.com and including the references to the jQuery library file in the HTML/PHP/JSP/Aspx page.
For example-
&amp;amp;amp;amp;amp;lt;script src="_scripts/jQuery-1.2.6.js" type="text/javascript"&amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;gt; &amp;amp;amp;amp;amp;lt;script language="javascript"&amp;amp;amp;amp;amp;gt; $(document).ready(function() { alert('test'); });
The jQuery serialize() method is used to create a text string in standard URL-encoded notation. It serializes the form values so that its serialized values can be used in the URL query string while making an AJAX request.
Syntax:
$(document).ready(function(){ $("button").click(function(){ $("div").text($("form").serialize()); }); });
The jQuery val() method is used:
To get the current value of the first element in the set of matched elements.
To set the value of every matched element.
Syntax:
$(document).ready(function(){ $("button").click(function(){ $("div").text($("form").serialize()); }); });
jQuery UI is a set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. jQuery UI works well for highly interactive web applications with different controls or simple pages with a date picker control.
The four parameters used for jQuery Ajax method are:
URL – You need to specify the URL to send the request.
Type – This specifies the type of requests such as Get or Post.
Data – It specifies the data to be sent to the server.
Cache – This decides whether the browser should cache the requested page.
The different ways to include jQuery in a page are:
Local copy inside script tag
Remote copy of jQuery.com
Remote copy of Ajax API
Local copy of script manager control
Embedded script using client script object
The jQuery html() method is used to change the entire content of the selected elements. It replaces the selected element content with new contents.
Syntax:
$(document).ready(function(){ $("button").click(function(){ $("p").html("Hello &amp;amp;amp;amp;amp;lt;b&amp;amp;amp;amp;amp;gt;edureka&amp;amp;amp;amp;amp;lt;/b&amp;amp;amp;amp;amp;gt;"); }); });
The jQuery CSS() method is used to set style properties or values for selected elements. It facilitates you to get one or more style properties. There are two ways to do the following:
Return a CSS property
It is used to get the value of a specified CSS property.
$(document).ready(function(){ $("button").click(function(){ alert("Background color = " + $("p").css("background-color")); }); });
Set a CSS property
This property is used to set a specific value for all matched element.
$(document).ready(function(){ $("button").click(function(){ $("p").css("background-color", "blue"); }); });
The jQuery UI Datepicker is a highly configurable plugin that adds datepicker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.
By default, the datepicker calendar opens in a small overlay when the associated text field gains focus. For an inline calendar, simply attach the datepicker to a div or span. You have to use the jQuery reference in your HTML code to make it work:
&amp;amp;amp;amp;amp;lt;head&amp;amp;amp;amp;amp;gt; &amp;amp;amp;amp;amp;lt;link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"&amp;amp;amp;amp;amp;gt; &amp;amp;amp;amp;amp;lt;script src="//code.jquery.com/jquery-1.10.2.js"&amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;gt; &amp;amp;amp;amp;amp;lt;script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"&amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;gt; &amp;amp;amp;amp;amp;lt;/head&amp;amp;amp;amp;amp;gt;
The slide methods do the up and down element. To implement slide up and down on element jQuery here are the three methods:
slideDown()
slideUp()
slideToggle()
slideDown() Method
This function is used to slide and hide an element on down side:
&amp;amp;amp;amp;amp;lt;script type="text/javascript"&amp;amp;amp;amp;amp;gt; $(document).ready(function() { $("#btnSlideDown").click(function() { $("#login_wrapper").slideDown(); return false; }); }); &amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;gt;
slideUp() Method
This function is used to slide and show element up side:
&amp;amp;amp;amp;amp;lt;script type="text/javascript" $(document).ready(function() { $("#btnSlideUp").click(function() { $("#login_wrapper").slideUp(); return false; }); }); &amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;gt;
slideToggle() Method
This method is between slideUp() method and slideDown() method. It is used to show or hide an element in up or down side:
&amp;amp;amp;amp;amp;lt;script type="text/javascript"&amp;amp;amp;amp;amp;gt; $(document).ready(function() { $("#btnSlideToggle").click(function() { $("#login_wrapper").slideToggle(); return false; }); }); &amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;gt;
The slice() method selects a subset of the matched elements by giving a range of indices. It gives the set of DOM elements on the basis of a parameter.
Syntax:
.slice( start, end[Optional] )
Start: This is the first and mandatory parameter of the slice method. This specifies from where to start to select the elements.
End: This is an optional parameter. It specifies the range of the selection. This indicates where to stop the selection of elements, excluding end element.
Delay comes under the custom effect category in jQuery. Its sole use is to delay the execution of subsequent items in the execution queue.
queueName is the name of the queue in which the delay time is to be inserted. By default, it is an “fx” queue. An “fx” queue is also known as an effects queue.
delay( duration [, queueName ] )
Arrays are zero indexed, ordered lists of values. They are really handy for storing a set of values of the same data type.
var names = [“Name1”,”Name2”]
Both of the preceding approaches are kind of static declarations. Now let’s do some dynamic programming with Arrays.
var namearray = []; namearray.push(“Name1”) //Index 0 namearray.push(“Name2”) //Index 1 namearray.push(“Name3”) //Index 2
Here, .push() is a jQuery function used in conjunction with Arrays that adds an element at the end of the array.
Plugins are a piece of code. The jQuery plugins are a code written in a standard JavaScript file. These JavaScript files provide useful jQuery methods that can be used along with jQuery library methods.
Any method you use in plugins must have a semicolon (;) at the end. The method must return an object unless explicitly noted otherwise. It produces clean and compatible code that way. You have to prefix the filename with jQuery, follow that with the name of the plugin and conclude with .js.
In $.map() you need to loop over each element in an array and modify its value whilst the $.Grep() method returns the filtered array using some filter condition from an existing array. The basic structure of Map() is:
$.map ( array, callback(elementOfArray, indexInArray) )
Syntax for $.Grep():
jQuery $.grep() Method
$ has no special meaning in JavaScript. It can be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, jQuery has no monopoly on use of $ which may create situations where you want to use it in conjunction with another JS library that also uses $. This would result in a naming conflict. jQuery provides the jQuery.noConflict() method for just this reason. Calling this method makes it necessary to use the underlying name jQuery instead in subsequent references to jQuery and its functions.
&amp;amp;amp;amp;amp;lt;div id="expander"&amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;gt; and the following CSS: div#expander{ width: 100px; height: 100px; background-color: green; }
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.
This can be written in jQuery as follows:
$( "#expander" ).animate( { width: "200px", height: "200px", }, 3000 );&amp;amp;amp;amp;amp;lt;/p&amp;amp;amp;amp;amp;gt;
Method chaining is a feature of jQuery that allows several methods to be executed on a jQuery selection in sequence in a single code statement. For example, the following snippets of code are equivalent:
Without chaining:
$( "button#play-movie" ).on( "click", playMovie ); $( "button#play-movie" ).css( "background-color", "red" ); $( "button#play-movie" ).show();
With chaining:
$( "button#play-movie" ).on( "click", playMovie ) .css( "background-color", "red" ) .show();
With chaining, the button only needs to be selected one time. Whereas, without chaining, jQuery must search the whole DOM and find the button before each method is applied.
jQuery.get() | jQuery.ajax() |
jQuery.get() is a shortcut method that uses jQuery.ajax() under the hood, to create an Ajax request that is typical for simple retrieval of information. Other pre-built Ajax requests are provided by jQuery, such as jQuery.post(), jQuery.getScript(), and jQuery.getJSON(). | jQuery.ajax() is the all-encompassing Ajax request method provided by jQuery. It allows for the creation of highly-customized Ajax requests, with options for how to handle a failure, whether the request is synchronous or asynchronous, what format to request for the response and many other options. |
The “jQuery.each()” function is a general function that will loop through a collection (object type or array type). Array-like objects with a length property are iterated by their index position and value. Other objects are iterated on their key-value properties. The “jQuery.each()” function however works differently from the $(selector).each() function that works on the DOM element using the selector. But both iterate over a jQuery object.
If we pass an array to each function, it iterates over items in the array and accesses both the current item and its index position.
Syntax-
jQuery.each(collection, callback(indexInArray, valueOfElement)) &amp;amp;amp;amp;amp;lt; script type = "text/javascript" &amp;amp;amp;amp;amp;gt; $(document).ready(function() { var arr = ["Mary", "John", "Garry", "Tina", "Daisy"]; $.each(arr, function(index, value) { alert('Position is : ' + index + ' And Value is : ' + value); }); }); &amp;amp;amp;amp;amp;lt; /script&amp;amp;amp;amp;amp;gt;
jQuery.attr()- It gets the value of an attribute for the first element in the set of matched elements.
jQuery. prop()– It gets 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. You can set an attribute for an HTML element and define it when writing the source code.
For example-
&amp;amp;amp;amp;amp;lt;input id="txtBox" value="Jquery" type="text" readonly="readonly" /&amp;amp;amp;amp;amp;gt;
Here, “id”, “type” and “value” are attributes of the input elements.
Chaining is a powerful feature of jQuery. This means specifying multiple functions and/or selectors to an element. Chaining reduces the code segment and keeps it very clean and easy to understand. Generally, chaining uses the jQuery built-in functions that make the compilation a bit faster.
For example:
$(document).ready(function() { $("#div2").html($("#txtBox").prop("readonly")) + '&amp;amp;amp;amp;amp;lt;/br&amp;amp;amp;amp;amp;gt;'; $("#div3").html($("#txtBox").attr("readonly")); });
$( "div" ).css( "width", "300px" ).add( "p" ).css( "background-color", "blue" );
This code uses method chaining to accomplish a couple of things. First, it selects all the <div> elements and changes their CSS width to 300px. Then, it adds all the <p> elements to the current selection, so it can finally change the CSS background color for both the <div> and <p> elements to blue.
jQuery has some important features that are used in web applications such as:
1. HTML/DOM Manipulation: JavaScript do not have any features related to the DOM, but JavaScript in the browser does include some intelligence about the DOM.
2. Event Handling: jQuery introduced a feature called Event handling. You can write code that runs when a user clicks on a certain part of the page, or when the mouse is moved over a form element. jQuery contains many events, such as a user clicking on a button, moving a mouse over an element, etc.
3. Ajax Support: When you select an item from a DropDownList or other control on the same page then that can cause loss of data. Ajax is used to update the part of the web page without reloading the page.
4. Animations in jQuery: The jQuery comes with plenty of built-in animation effects that you can use in your websites. For example, animation, show, hide and so on. In jQuery, the animate() method is used to perform such tasks.
With this, we have come to the end of jQuery interview questions blog. I Hope these jQuery Interview Questions will help you in your interviews. In case you have attended any such interview in the recent past, do paste those interview questions in the comments section and we’ll answer them. You can also comment below if you have any questions in your mind, which you might face in your jQuery interview.
Check out our Full Stack Web Developer Masters Program which comes with instructor-led live training and real-life project experience. This training makes you proficient in skills to work with back-end and front-end web technologies. It includes training on Web Development, jQuery, Angular, NodeJS, ExpressJS and MongoDB.
Got a question for us? Please mention it in the comments section of “jQuery Interview Questions” blog and we will get back to you.
edureka.co