JQuery Interview Questions

Oct 13, 2022
100 views
46 questions

About Jquery

jQuery is a fast, lightweight, and concise JavaScript library that supports all browsers. It is easy to play with DOM, event handlings, animations, and AJAX interactions for fast web development with jQuery. Its slogan "minimal lines of code" helping the developers to write a few lines of code to do the most things.

Key Features of Jquery

  Easy DOM Manipulation
  Support AJAX
  JSON Parsing
  Extensible Through Plug-ins
  Cross-browser Support
  Easy Integration
  Lightweight
  Event handling & Animation
  Protection Against XSS Attacks

JQuery Interview Questions for Freshers

Jquery is a fast, lightweight, cross-platform Javascript library that simplified the traversal and manipulation of DOM.

It is also capable of performing event handling, CSS animation, validation, and Ajax. Jquery is design by John Resig and available as a free, open-source library under a permissive MIT License.

Jquery is widely used for

  • Creating Javascript Plugins
  • Manipulation of DOM
  • Performing client-side validation
  • Updating content asynchronously using AJAX.
  • Doing CSS Animations

Jquery is a fast, lightweight, cross-platform Javascript library that simplified the traversal and manipulation of DOM.

It is also capable of performing event handling, CSS animation, validation, and Ajax. Jquery is design by John Resig and available as a free, open-source library under a permissive MIT License.

Jquery is widely used for

  • Creating Javascript Plugins
  • Manipulation of DOM
  • Performing client-side validation
  • Updating content asynchronously using AJAX.
  • Doing CSS Animations

In jQuery the is() method is used to check if one of the selected elements matches the selectorElement. selector. It is an optional parameter that specifies the selector from which event will remove.

Yes, Jquery case sensitive library. You must take care of the case while using functions, variables, and other identifiers.

For example

“date()” and “Date()” is not the same.

jQuery is a library of Java which is lightweight and user can do more with it by writing less amount of code. The goal of jQuery is to ease the usage of Javascript for any user’s website to a great extent.jQuery renders another benefit of streamlining a large number of complicated things of the Javascript, for example, AJAX calls, DOM manipulation and many more.

The jQuery, a library of Javascript contains the below-mentioned features:

  • HTML/DOM manipulation
  • HTML event methods
  • AJAX
  • CSS manipulation
  • Utilities
  • Effects and animations

There are two main ways to add a jQuery to your project

Download the jQuery package from the jQuery official website and store it in your applications folder. Then, use the following script to include jQuery in your application.

<head> 
<script src="jquery-3.4.1.min.js"></script> 
</head> 
The second way is to include jQuery from a CDN like Google, Microsoft, etc. 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>  //Google CDN 
</head> 

The $(document).ready() is a listener that is executed whenever the document is loaded and the page DOM is ready to be executed. The method is loaded only after the whole DOM is ready but before all the images, and other resources are loaded in the document. A document can have multiple document ready listeners.

//syntax 
$(document).ready(function() { 
   //DOM manipulation code 
}); 

Some of the common DOM event handling methods are,

  • Onclick – to handle when a DOM element is clicked.
  • Ondblclick – to handle when a DOM element is double-clicked.
  • Onload – to handle when a document is loaded.
  • Onerror() - to handle the browser error event.
  • Onsubmit – to handle when a form is submitted.
  • Onselect – to handle when an element is selected in form.

Bubbling is a scenario in which if an event is called for a child element, the parent element will also be called if it is set up with an event as well. To stop this propagation, jQuery has an inbuilt method called as event.stopPropagation(). This method stops popup for other elements other than the selected element.

//syntax 
Event.stopPropagation() 

jQuery statement always starts with ‘$’ sign. It is an alias for jQuery that defines the jQuery.

//syntax 
$(selector).action() 
//example 
$("p").hide()  //hides the paragraph. 

$ is an alias for jQuery. It is an object that has jQuery properties and we can use it to call it.

For eg: $.Ajax() - used to perform AJAX requests.

$() is an alias for jQuery(). It is a function to converts the DOM elements into a jQuery objects by searching the DOM to match the provided selector.

For eg: $(“#id”) - It finds the DOM object matching the selector ‘id’ and converts to jQuery object for further manipulation in JavaScript.

The compound selector in jQuery is used to select multiple elements using a single select expression. Any number of selectors can be provided to the jQuery statement separated by comma to get a single combined result.

//format 
jQuery( "selector1, selector2, selectorN" ); 
//example 
$( "div, span, h2" ).css( "border" ); //here the border is applied to two elements. 

Empty() method and remove() method are both used to remove elements with one difference.

Empty() method deletes the content of the selection.

Remove() method deletes the content of the selection with selection also.

//example 
<p><h1>hello</h1></p> 
$(‘p’).empty(); deletes only the h1 tag. 
$(‘p’).remove(); deletes both the selected p tag and its child h1 tag. 

The double click method in jQuery is used to handle when an element is double clicked. The dbclick() triggers the double click event in for an element. A function can be attached to it to implement further process when an element is double clicked.

//syntax 
$(selector).dblclick() 
$(selector).dblclick(function) //function is optional. 
 
//example 
<script> 
$("p").dblclick(); 
</script> 
<body> <p ondbclick = “alert(‘dbclick event’)”>Paragraph</p> 

In the above example, the paragraph is linked with the double click event. So, when it is double clicked the ‘dbclick event’ will be displayed.

Selectors in jQuery are used to select and manipulate HTML elements. It selects the HTML elements based on their name, id, classes, types, attributes, and much more.

jQuery selectors help you to select and manipulate HTML Elements. They are :

  • Basic jQuery Selectors
  • Content jQuery Selectors
  • Hierarchy jQuery Selectors
  • Selectors based on Index
  • Visibility Selectors
  • Child Selectors Attribute Selectors
  • Content Selectors
  • Form Selectors
Example 
$(“p”) -> Here the element is selected based on its name. 
$(“#id”) -> Here the element is selected based on its id. ‘#’ is used to imply the id. 
$(“.className”) -> It selects the element based on its class. ‘.’ is used to imply the class name. 

Remove() and detach() are both used to delete the elements with a small difference in implementation. Remove method deletes the content, and data with the selected element. The deleted element or the data cannot be restored as the elements are removed from the DOM element. Detach method is like the remove method is deleting but it keeps the data and element without removing completely. The detached elements can be reinserted by using the appendTo method.

Example 
$(‘p’).remove(); //removes the element completely. 
Var p = $(‘p’).detach(); //removes the element but it is stored in variable ‘p’. 
p.appendTo(‘body’); //the removed data and the element can be reinserted at any time. 

The bind method is used to register the type of event and event handler to the DOM element that matches the given selector. It registers the event handler to all the DOM elements that match the selector given. It will not add the event handler to the future element created that has the matching selector.

//example 
$( "img" ).bind( "click", function( e ) {/* statements */} ); //Here the event handler is registered to only the current DOM elements that are matched with “img”.

The live method works same as bind method but it registers the event handler to current matching elements, as well as future element that you add.

//example 
$('img').live('click', function() { /* Statements*/ }); //here img is the selector that is matched to all the curent and future DOM elements. 

The filter method in the jQuery is used to filters the elements based on the criteria given to the function.

//syntax 
$(selector).filter(criteria, function(index)) 

Here, the elements that match the criteria is given to the function to run further logic on it.

//example 
$(“li”).filter(“#id1”).css(“color”, “blue”); 

In the above example, the list element with id1 is filtered from the list and is applied with the css function to change its color.

‘this’ is a DOM object that is, it a reference to the HTML DOM element. You can call DOM methods with this object but not jQuery methods.

$(this) is a jQuery wrapper around the DOM object to use the jQuery method on it. You cannot call DOM methods with $(this).

jQuery(“*”) is used to select all the elements in the document. You can do all the jQuery methods on this selector. So, it applies the method to all the elements in the document.

//example 
$(“*”).hide() -> it hides every element in the document. 

Some jQuery filters used in the form are,

Find() function filter the element that match with the specified selector.

//example
$("form").each(function(){
    $(this).find(':input') // -> it returns all the inputs in the specified forms.
});
Contains() function selects only the elements containing the specified string.

The hasClass() method is used to check if the element has a class name or not. If the specified element has a class name, then it returns true or false.

//syntax 
$(selector).hasClass(classname) 
 
//example 
<p class="className">paragraph.</p> 
$("p").hasClass("intro"); //this function returns true as the ‘p’ tag has class name. 

Advantages of using jQuery:

  • Create Responsive websites using AJAX
  • Allows creation of dynamic web pages and web applications
  • Extendable
  • Manages cross-browser issues
  • Light-weight entity
  • DOM Manipulation
  • Fast
  • Implementing complex functionalities by writing lesser lines of code
  • Easy and readable code
  • No overhead in learning a new syntax
  • Avoids common browser errors

The major difference between Javascript & jQuery is as follows:-

  • JavaScript is a programming language, while jQuery is a javascript library.
  • One should know JavaScript prior to using jQuery.
  • In JavaScript, you need to write a long code. Whereas jQuery can perform the same function in very fewer lines of code.
  • JavaScript is faster for accessing DOM. jQuery is slower.
  • Developers are prone to make browser-related errors in JavaScript. Whereas jQuery developers don’t have to worry about browser compatibility issues.

$() in jQuery a syntax in jQuery which is used to select the Html elements or collect matching elements from DOM.

Example,

$(‘#id’) for selecting element by id
$(‘.classname’) for selecting element by class

AJAX stands for (Asynchronous JavaScript and XML). It is a process of exchanging data with a server and refreshing the whole page and updating applied changes without reloading the whole page.

jQuery ajax() method helps to send asynchronous HTTP requests to the server.

Param() method in jquery creates a serialized representation of an array or an object from element values. The object stands for an array or a plain object or an object to serialize. Traditional has type Boolean indicating to perform a traditional "shallow" serialization.

Syntax :

$.param(object,trad)

bind() attaches events to elements that exist or match the selector at the time the call is made i.e will only apply to the items you currently have selected in your jQuery object.

.live() works for existing and future matching elements i.e will apply to all current matching elements, as well as any you might add in the future.

.delegate() method adds one or more event handlers to the specified element.

List some effects methods used in jQuery are as follows:-

  • Animate() - Used to customize animations on any selected elements
  • Clearqueue() – Used to remove any remaining queued functions from the selected elements.
  • Delay() – to set a delay for all queued functions of the selected elements.
  • Fadein()– fades in the selected elements.
  • Fadeout() – fades out the selected elements.
  • Fadeto()– to fade in/out the selected elements to a required opacity.
  • Dequeue() – to execute the functions after removing the next function from the queue.
  • Fadetoggle() –to toggle between fadeout() and fadein() methods.
  • Finish() – to stop, remove and complete any/all queued animations for the selected elements..

The jQuery toggle() is a type of method which is used to toggle between two or more functions such as the hide() & show() method

  • Show() is used to show the hidden elements.
  • Hide() is used to hide the visible elements.

The Css() method in jQuery is used to set or return style properties of one or more styles for the selected elements. It is an easy way to get the computed style properties for the elements in the set of matched elements.

jQuery is a plugin that is used to connect or bind a function to another function. It is more of assigning a handler for another function. It is used to execute a function when a function from another plugin is executed.

The ID and class selector in jQuery helps to find and select DOM elements easily. The class selector is used in case we need to select multiple elements, which have the same CSS class. Searching and finding HTML elements using selectors are natural and very easy.

Serialize() method serializes a set of input elements into a string of data. It creates a URL encoded text string by serializing form values. The serialized values can be used in the URL query string while making an AJAX request.

Syntax : 
$(selector).serialize()

Event.stopPropogation() is used for stopping event propagation. It prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. You can use the event.isPropagationStopped() method to check whether this method was called for the event.

 

Syntax : 
event.stopPropagation()

The animate() method performs custom animation of a set of CSS properties. 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 : 
(selector).animate({styles},speed,easing,callback)

The speed parameter specifies the duration of the effect.

The callback parameter is a function to be executed after the animation completes.

In jQuery, reading, writing, and deleting cookies are done by using the dough cookie plugin.

The syntax for reading cookie :

$.dough(“cookie_name”);

The syntax for writing cookie :

$.dough(“cookie_name”,”cookie_value”);

The syntax for deleting cookies

$.dough(“cookie_name”,”remove”)

jQuery UI is a set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. jQuery UI is the perfect choice for building highly interactive web applications and to add a date picker to a form of control. It contains many widgets that maintain state and therefore have a slightly different usage pattern than typical jQuery plugins. All of jQuery UI's widgets use the same patterns, so if you learn how to use one, then you'll know how to use all of them.

The slice() method reduces the set of matched elements to a subset specified by a range of indices

Syntax : 
.slice(start[,end])

A start has a type integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. The end has a type integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set.

To set any form value of an element using jQuery val() function is to be used.

Here is a demonstration of how to set content with the jQuery val() methods:

$(“#btn”).click(function(){
	$(“#test”).val(“hello”);
});

This jQuery method also comes with a get/return/callback function. The callback function has two parameters: the index of the current element and the original (old) value. A user then returns the string they wish to use as the new value from the function.

A page to be manipulated safely needs the document to be ready. jQuery detects this state of readiness for you. A page document object model (DOM) which is ready for javascript code to execute includes inside $(document).ready(). Code included inside $(window).on("oad",function(){…}) will run once the entire page, not just the DOM, is ready. A developer sometimes can use the shortform $() for $(document).ready(). Example: chaining together the css(), slideup() and slidedown() meth

jQuery allows users to chain together actions/methods. Chaining allows users to run multiple jQuery methods within a single statement. This technique of chaining allows us to run multiple jQuery commands, one after the other, on the same elements.

This helps browsers by reducing the time to find the same element more than once. A chain an action user appends the action to the previous action.

The following example uses how to get the value of the href attribute in a page:

 
$(“button”).click(function(){
	Alert($(“#w3s”).attr(“href”));
});

The unbind() method removes event handlers from selected elements. The unbind() function removes all or selected event handlers, or stops specific functions from running when the event occurs. This is used to unbind an event from within itself.

This method works on any event handler attached to jQuery.

$(selector).unbind(event,function,eventObj)

This function can be used to seamlessly iterate over both objects and arrays. An object with a length property is iterated by a numeric index from 0 to 1. The $.each() function is different from the $(selector).each() which is used to iterate over a jQuery object.

For example:

$.each([50,9],function(index, value){
	Alert(index + “:” +value);
});

This produces two messages:
0: 50
1: 9

In jQuery, there are mainly three selectors, which are ID, class, and attribute. Among these, Id selector is the fastest of all, the reason being that ID is supposed to be unique, so the searching stops after ID is found on the Document object model. Whereas, class and attribute search through the entire page to find the required match taking a bit longer than ID selector.

The data() method gives the user the ability to attached data to or gets data from, within DOM nodes and Javascript objects. When a user uses the data method, the user needs to pass two parameters such as key and a value to be stored.

Difference between Jquery & DOJO?

jQuery DOJO
It is a JavaScript library It is a JavaScript toolkit. JQuery is licensed by MIT. The dojo is licensed by BSD or AF. It was started at Rochester Institute of Technology in January 2006 by John Resig. It was released in 2004 by Dylan Schiemann, David Schontzler and Alex Russell.
JQuery presents User Interface libraries with many beneficial functionalities Dojo toolkit provides the features of a widget toolkit.
JQuery is used mostly for web application and dynamic web pages. Dojo is used for web-oriented software on desktop, mobile and internet applications.
JQuery is being used by WordPress, BackBone, Wikipedia, etc. Dojo is being used by internet browsers like Internet Explorer, Google Chrome, Safari, etc.
JQuery is lightweight with 19K compressed base libraries. Dojo provides many customizing choices but it is a massive and complex toolkit.
JQuery requires a less network bandwidth than Dojo. Dojo requires a higher network bandwidth than JQuery.

Advantages of jQuery

  • Open source library: JQuery is an open source library for all types of application. What a developer wants more than this, anyone can use it for their applications without any license or agreement issues.
  • Lightweight: The size of the jQuery core library is just 24kb which can be easily added to any application and hence, increase the performance. The reason behind the lightweight jQuery library is limited functions. Some functions are omitted from the library and some are transferred to plug-ins. So that whenever these functions required, developers can add those plugins in their applications.
  • Limited Coding level: As the slogan of jQuery “few lines of code, do the most things” explains by itself. The use of advanced selectors in jQuery lets the developers write just a few lines of code and obtain the desired result. Thus, jQuery took the JavaScript to a higher level.
  • Browser compatibility: It is the utmost advantage of jQuery, as this is the biggest problem that any developer face in other designs. For example, in JavaScript, when you write code for one browser, it may not run on another browser properly. So, the designers of jQuery fixed this problem and help the developers to write the same code for all browsers.
  • Plug-ins: jQuery provides the thousands of plug-ins to perform the tasks such as validation, animation, field prompt and many more. It doesn't stop here; you can also create your own plug-ins and also can share with other developers. To create the plug-in is very simple, just use the framework given to extending the library.
  • Flexible: jQuery is compact but easy to learn. If you want to understand jQuery, then you just need to give a little bit of your time. You will be able to write the codes and independent widgets very easily after going through a short tutorial on jQuery.
  • jQuery is a fun: jQuery is very powerful and precise language. Using jQuery for programming gives you the desired result very quickly. It solved the many challenges and issues of JavaScript. Many fundamental tools are improved and many new are designed which developers can use to generate next level web applications.
  • Animations: You can easily avail cool effects such as contrast/expand, fade out, etc. in designing the application by writing just a couple of lines of code.

Disadvantages of jQuery

  • Limited Functionalities: In spite of the powerful library, but sometimes it is necessary to use the raw JavaScript. Functionalities may be limited that depends on how much personalization; you want in your application.
  • Backward compatibility: Sometimes, the new version is not compatible with the previous version. For instance, the newer version has removed some selectors which are previously widely used. This may confine the developers to upgrade their application from an old version to a newer one.
  • Plugins compatibility: Similar to backward compatibility, developers need to check the plugins supported by the newer version before upgrading. Sometimes, the existing plugins are not supported by the newer versions at all. Also, while using multiple plugins on the same page, can encounter some conflicts.
Share this post