Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is jQuery used for?
3.
Commonly Asked jQuery Interview Questions
3.1.
1. What is jQuery?
3.2.
2. What are the different tasks or operations that jQuery can do?
3.3.
3. What are the differences between jQuery and Javascript?
3.4.
4. What is the “$()” Function in jQuery library?
3.5.
5. What is the starting point of the code execution in jQuery?
3.6.
6. What are the commonly used jQuery methods for creating various effects or animations?
3.7.
7.What is the use of the toggle( ) method in jQuery?
3.8.
8.  Does jQuery work for both HTML and XML documents?
3.9.
9. What is the use of the html() method in jQuery?
3.10.
10. What is the use of the CSS() method in jQuery?
3.11.
11. What is the addClass() method in jQuery?
3.12.
12. What are the advantages of jQuery over javascript?
3.13.
13. What is the use of jQuery.length?
3.14.
14.  What is jQuery UI?
3.15.
15. What is chaining in jQuery?
3.16.
16. What is the difference between $(window).load and $(document).ready function in jQuery?
3.17.
17. How can we select the parent element of a given element using jQuery?
3.18.
18. How do we check if an element exists or not in DOM?
3.19.
19. How can we remove a specific attribute from an element using jQuery?
3.20.
20. What is Event Propagation in jQuery?
3.21.
21. How can we serialize form data using jQuery?
3.22.
22. What is the use of ‘animate()’ in jQuery?
3.23.
23. Explain the promise() method in jQuery?
3.24.
24. What is the use of jQuery Connect?
3.25.
25. How can you optimize the jQuery selectors for better performance? 
3.26.
26. How does jQuery handle AJAX errors using the '.ajaxError()’ method?
3.27.
27. How can we bind multiple events to an element using jQuery?
3.28.
28. Is it possible to filter elements based on specific criteria?
3.29.
29. What are the various methods to make AJAX requests in jQuery?
3.30.
30. How can we handle the response of AJAX requests using jQuery?
3.31.
31. What is the purpose of the ‘$.extend()’ function in jQuery?
3.32.
32. What is the use of the “event.preventDefault()” method in jQuery?
3.33.
33. Explain the concept of method overriding in jQuery plugins.
3.34.
34. How does event delegation work in jQuery?
3.35.
35. Is it possible to trigger an event using a method or a property of jQuery?
4.
jQuery Coding Questions
4.1.
36. How to change the text value of the button on the click?
4.2.
37. How to retrieve the text content of the specific element with its class using jQuery?
4.3.
38. How to retrieve the length of the text value of the ‘p’ tag using jQuery?
4.4.
39. How to change the content of the 'p' tag after clicking the button using jQuery?
4.5.
40. How to append text content to the ‘p’ tag on clicking the button using jQuery?
4.6.
41. How to change the background color of ‘p’ tag on clicking a button using jQuery?
4.7.
42. How to display an alert box on a button click using jQuery?
4.8.
43. How to retrieve input text value on clicking a button using jQuery?
4.9.
44. How to retrieve the width of the div on clicking a button using jQuery?
4.10.
45. How to display the current time on the alert box using jQuery?
5.
Frequently Asked Questions
5.1.
What is the main focus of jQuery?
5.2.
Which operating system is more compatible with jQuery?
5.3.
What is the starting point of jQuery?
5.4.
Is jQuery a library for client scripting?
6.
Conclusion
Last Updated: Jun 12, 2024
Easy

Top 40+ jQuery Interview Questions and Answers (2024)

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Welcome to this new blog on jQuery Interview Questions. Whether you're a seasoned developer or preparing for a jQuery-focused interview, this blog will equip you with essential insights and responses to excel in discussions about jQuery, a powerful and widely used JavaScript library. 

Top JQuery Interview Questions in 2023

This article covers all the essential jQuery Interview Questions big tech companies ask. We have divided the questions into three categories: beginner, intermediate, and advanced. This article is for you if you lie in any of these categories.

What is jQuery used for?

Basically, jQuery is used to make the process of writing Javascript better than ever. Here are some of the points that show what jQuery is used for:

  • jQuery is used to create a dynamic website.
     
  • jQuery is used to reduce the JavaScript redundant code.
     
  • jQuery is used to keep the code simpler and more readable.
     
  • As SEO(Search Engine Optimization) is also an important concern while creating a website, jQuery is used to optimize search engines.
     
  • If the developers do not want to write plug-ins by themselves, jQuery is used because it provides plug-ins for almost every task.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Commonly Asked jQuery Interview Questions

1. What is jQuery?

JQuery is a widely used open-source library that simplifies the process of interactions between HTML Documents or CSS Documents and implements AJAX (Asynchronous Javascript and XML) functionality. With the help of Jquery, we can do various operations on web pages, including selecting or manipulating the elements and making HTTP requests.

2. What are the different tasks or operations that jQuery can do?

  • It allows us to apply multiple operations to an element in a single line of code.
     
  • It makes the modification of DOM elements and their properties more simple.
     
  • We can quickly navigate the DOM tree to find any element.
     
  • It allows us to make Asynchronous HTTP requests and fetch the data in various formats such as JSON and XML.
     
  • It provides an animation method that helps us animate CSS properties.

3. What are the differences between jQuery and Javascript?

jQueryJavascript
It is a Javascript library or framework.It is a dynamic and interpreted language for web development.
It has more concise code which achieves the same results in a few lines of code.It requires more lines of code for accomplishing some task.
It provides direct access to the DOM which helps to manipulate the web page elements.It provides a concise and consistent API for accessing and modifying the DOM elements.
The URL of the JQuery library must be included in the page’s header.All browsers support Javascript. There is no need for other plugins.
There is no need to deal with multi-browser compatibility troubles.We write the code to handle multi-browser compatibility.

4. What is the “$()” Function in jQuery library?

The $() Function is an abbreviation for the jQuery() Function. It can take different parameters such as HTML tags, class names, CSS selectors and many more. For example, “$(.current_class)” can select all the elements of the ‘current_class’ and returns the jQuery object containing all those elements.

5. What is the starting point of the code execution in jQuery?

The starting point of code execution is within a ready() method. It is executed when the DOM is loaded and ready to be manipulated. This prevents errors when we try to manipulate the elements before they exist in the DOM.T

6. What are the commonly used jQuery methods for creating various effects or animations?

The commonly used jQuery methods for creating various effects or animations are:

  • toggle() : It toggles the visibility of the selected elements. 
  • show() : It shows the selected elements.
  • hide() : It hides the selected elements.
  • stop() : It stops the current animation for the elements that have been selected.
  • slideDown() : It slides-down (shows) the selected elements.
  • slideUp() : It slides-up (hides) the selected elements.

7.What is the use of the toggle( ) method in jQuery?

Toggle an element's visibility, use the jQuery toggle() method. Depending on whether the element is hidden or visible, it calls either the show() or hide() method after checking the element's current visibility.

Recommended Topic: Kotlin Interview Questions

8.  Does jQuery work for both HTML and XML documents?

JQuery was initially intended to solely function with HTML documents. There are a couple techniques for utilising jQuery with XML documents, though.

One option is to convert an XML document into a jQuery object using the jQuery.parseXML() method. The XML document can then be modified using this object and jQuery functions.

Using the jQuery.XPath() method to pick elements in an XML document is another approach to utilise jQuery with XML documents. Using this technique, elements can be chosen based on their XPath expressions.

9. What is the use of the html() method in jQuery?

We use the html() method to update the selected elements. It sets or returns the HTML content of an element.
 
Syntax to get the HTML content of an element:

let varname = $(selector).html();

Here, the variable “varname” stores HTML content of the first matched element selected by the selector.

Syntax to set the HTML content

$(selector).html(content);

Here, the HTML content of the first matched element selected by the selector will be replaced by the content passed in this function.

10. What is the use of the CSS() method in jQuery?

The css() method is used to alter the style properties of the selected element. We can get or set the CSS properties of the selected element. 

Syntax to get the CSS property

let content = $(selector).CSS(property-name);

Here the CSS method is used to retrieve the ‘property-name’ CSS property of the first matched element selected by the selector.

Syntax to set the CSS property

$(selector).CSS({property-name : value});

Here the CSS method sets the ‘property-name’ to the ‘value’ for the element selected by the selector.

11. What is the addClass() method in jQuery?

The addClass() method is used to add one or more classes to the selected element.

Let’s see an example to understand its use case.

/* to add a single class */
$('#nav_id').addClass('class1');

/* to add multiple classes */
$('#nav_id’').addClass('class1 class2 class3 class4');


Here we are adding CSS classes to the element with the ID ‘nav_id.’ To add a single class, write its name in a string format, and to add multiple classes, you just need to add spaces between the class names in a string format.

12. What are the advantages of jQuery over javascript?

The following are some benefits of jQuery over JavaScript:

Shorter code: jQuery offers a number of quick cuts that allow for more concise and shorter code than JavaScript. Instead of using the lengthier and verbose document to pick elements, one can use the jQuery $(selection) selector.JavaScript's selector() function.

Simpler to learn: Even for novices, jQuery is designed to be simple to understand. Although it is shorter and simpler than JavaScript, the grammar is similar.

Cross-browser compatibility: All popular browsers, including Chrome, Firefox, Safari, Edge, and Internet Explorer, are compatible with jQuery. Without having to write any browser-specific code, you can be sure that your code will function on all browsers.

Reusable code: jQuery offers several methods and functions that can be used repeatedly to carry out common tasks like event handling, animation, and Ajax calls. You can save time and effort by doing this while creating web applications.

Large community: jQuery has a sizable and vibrant developer community that offers help and documentation. If you need assistance with your jQuery code, this may be useful.

13. What is the use of jQuery.length?

It is a property to count the number of elements that match the selector. It is not a method so we do not use parentheses here.

Syntax of jQuery.length

let count = $(selector).length;


Here the selector selects all its elements and the length property takes account of all these elements.

14.  What is jQuery UI?

Built on top of the jQuery JavaScript Library, jQuery UI is a selected collection of user interface interactions, effects, widgets, and themes. It offers a collection of pre-built widgets and interactions that may be used to build web apps that are both highly interactive and user-friendly.

A few of jQuery UI's features are as follows:

Widgets: jQuery UI offers a variety of widgets, including dialogue boxes, sortable lists, and datepickers. Without writing any JavaScript code from scratch, these widgets can be utilised to build intricate user interfaces.

Interactions: Drag and drop, resizable elements, and sortable lists are just a few of the interactions that jQuery UI offers. You can utilise these interactions to provide your web pages dynamic behaviour.

Effects: JQuery UI offers a variety of effects, including rotating, sliding, and fading. You can use these effects to give your web pages more visual flair.

Themes: You can alter the look and feel of your web pages by using one of the many themes that jQuery UI offers.

15. What is chaining in jQuery?

Chaining is a technique used to execute multiple methods within a single sentence. Instead of writing separate lines of code for different methods, chaining makes it more concise and we can run several methods in a single sentence. 

Let’s see an example to get a gist of chaining.

$(‘#nav_id’)
.hide()
.CSS(‘Text-color’, ‘Blue’)
.show();


In this example, the selector selects the elements with the id ‘nav_id’. The methods including hide(), CSS(), show() are called on the selected elements in a sequence.

16. What is the difference between $(window).load and $(document).ready function in jQuery?

$(document).ready:

  • fires before pictures and other external resources, once the DOM has loaded completely.
  • suitable for binding event handlers and altering the DOM structure.
  • Because it doesn't wait for outside resources, it executes more quickly.

 

$(window).load:

  • fires once all material, including external resources and graphics, has finished loading.
  • suitable for jobs that require access to the entire page, like obtaining image dimensions.
  • execution is slower while it waits for all resources to load.
     

17. How can we select the parent element of a given element using jQuery?

We can select the parent element of a given element by using the '.parent()’ method. To select the immediate parent, we use the '.parent()’ method and to select all the ancestors of an element, we use the '.parents()’ method.

Syntax to select the parent and ancestor at any level:

let immediateParent = $(selector).parent();
let ancestorElement = $(selector).parents();

18. How do we check if an element exists or not in DOM?

To check whether an element is present in DOM, we use jQuery's '.length' property. If the length is greater than zero, it indicates that the element is present. Otherwise, it means that the element is absent in DOM.

For example:

let exist = $('.myid').length;
If (exist) console.log(“Element is present”);
else console.log(“Element is absent”);

19. How can we remove a specific attribute from an element using jQuery?

We can use the '.removeAttr()’ method to remove a specific attribute from an element.

Syntax to remove an attribute from an element:

$(selector).removeAttr(attribute-name);


This method will remove the ‘attribute-name’ attribute from all the elements selected by the selector.

20. What is Event Propagation in jQuery?

Event Propagation is a technique through which events travel through the DOM tree to their destination. It determines how an event occurring on one element can affect it’s children elements and parent elements. 

There are three stages of Event Propagation:

1. Capturing Phase: The event begins at the root of the DOM tree and moves downwards until it gets a target element (event.target).

2. Target Phase: when the event has reached the target element.

3. Bubbling Phase: The event bubbles up from the target element and triggers the event handlers of its ancestors until it reaches the root of the DOM tree. 

21. How can we serialize form data using jQuery?

To serialize a form data, we can use the '.serialize()’ method or the ‘serializeArray()’ method.

This method collects all the values of the form elements and creates an encoded string of the form data. 

Let’s see the use cases of these methods.

let Data = $(selector).serialize();
let DataArray = $(selector).serializeArray();


Here the selector is selecting the form elements and the ‘.serialize()’ method is collecting the data from the form fields and returning the data in the form of encoded string whereas the '.serializeArray()’ method is returning an array of objects representing the form data.

22. What is the use of ‘animate()’ in jQuery?

The ‘animate()’ is a jQuery method that is used to create smooth animations by changing the CSS properties of selected elements over a duration specified in this method. 
Let’s see the syntax of an animation method.

$(selector).animate(
   { CSS_Properties },
   animation_duration,
   easing_function,
   function () {
       // animation is over
   }
);


Here the first parameter specifies the CSS properties and their target values,  the second parameter specifies the duration of animations, the third parameter is the easing function, and the last one is a callback function that will execute once the animation completes.

23. Explain the promise() method in jQuery?

The .promise() method produces a dynamically generated Promise that can be resolved once all actions of a given type connected to the collection, whether queued or not, have been completed. It allows us to synchronize and control the execution of asynchronous operations. 

Let’s take a look at its syntax.

$(selector).promise();


The selector will select the element for which we want to create a promise object. The promise will be attached with the deferred object created by the last animation.

24. What is the use of jQuery Connect?

jQuery Connect is a plugin that binds or links one Function to another. It’s comparable to assigning a handler to another function. JQuery Connect also enables users to connect a function to a DOM object. You can use Connect to bind more than one Function.

For example:

$.connect(object1, ‘function1’, object2, ‘function2’);


In this case, we are connecting the function ‘function2’ of the object ‘object2’ with the function ‘function1’ of the object ‘object1’.

25. How can you optimize the jQuery selectors for better performance?
 

  • ID selectors make our program faster because of their higher specificity.
     
  • Do not use class selectors like ‘$(“div”)’ and ‘$(“span”)’ because they are very generic and make our program a bit slower.
     
  • Use direct descendant selectors (>) if elements are direct children because they reduce the search space and improve the performance.
     
  • Sometimes using native DOM methods are faster than using jQuery selectors.

26. How does jQuery handle AJAX errors using the '.ajaxError()’ method?

To handle the AJAX errors, we bind the global event handler to the ‘ajaxError’ event on the ‘document’ object. So whenever we encounter an AJAX error, the handler will be triggered and we can perform our error handling logic inside the function.

Below is the AJAX error handling function.

$(document).ajaxError(function (Event, XMLhttpRequest, Error) {
   // write your error handling logic here
});

27. How can we bind multiple events to an element using jQuery?

We can bind multiple events to an element by using the '.on()’ method. All these events should be written in the string format separated by spaces.

Let’s see an example to understand the binding of events to an element.

$("#my_id").on("enter scroll mouseleave", function (Event) {
   // write the event handler function logic here
});


Here we are binding three events to an element with the id “my_id”. To execute this callback function, three of any events should occur on the element with the id “my_id”.

28. Is it possible to filter elements based on specific criteria?

It is possible to filter the elements based on specific criteria using the '.filter()’ method, selectors, and custom filtering functions.

Let’s take an example to understand filtering based on some condition.

$("span").filter(function () {
   return $(this).hasClass("pathfinder");
}).addClass("filtered_elements");


This filter method is using a function which is checking if the ‘<span>’ element has a class “pathfinder”. If the condition evaluates to true, the matched elements will be assigned to a class “filtered_elements”.

29. What are the various methods to make AJAX requests in jQuery?


The various methods to make AJAX requests in JS are:

load(): Load a snippet of HTML into a DOM container.

$.getJSON(): Use the GET method to load JSON.

$.getScript(): Load a Javascript file.

$.get(): It is used to make a GET request and manipulate the response.

$.post(): It is used when we want to perform a POST call but don’t want to load the response into the DOM container.

30. How can we handle the response of AJAX requests using jQuery?

To handle the response of AJAX requests we can use different methods including ‘.done()’, ‘.fail()’ and ‘.always()’. These methods allow us to take some actions when an AJAX request succeeds, fails and is independent of the outcome.

The example below shows how to handle the response of AJAX requests using jQuery.

$.ajax({
   // make an ajax request
})
.done(function (Response) {
   // handler for a successful response
})
.fail(function (httpRequest, status, error) {
   // handler for a failed response
})
.always(function () {
   // perform actions after request completes
});

31. What is the purpose of the ‘$.extend()’ function in jQuery?

The ‘$.extend()’ function is used to merge the contents of two or more objects into the target object. It offers a practical method of combining various objects, replacing features and increasing functionality.

The syntax of ‘$.extend()’ function is:

$.extend(TargetObject, object1, object2, object3, …);
Here the ‘TargetObject’ is the final object which contains the merged data of all the given objects.

32. What is the use of the “event.preventDefault()” method in jQuery?

The “event.preventDefault(): method prevents the default behaviour associated with an event. By invoking this method inside the event handler, we can prevent the browser from executing the default action corresponding to an event. When events like submitting a form and clicking a link occur, the browser follows the default actions for these events. By using the method “event.preventDefault()”, we can inform the browser to not perform these default actions and thus we override the default behaviour of the events.

33. Explain the concept of method overriding in jQuery plugins.

It is an ability to change or expand the behaviour of already specified methods. It allows us to alter the operations of the plugin by changing the functions with our own implementations.
The jQuery plugin provides us with various methods that carry out a particular task, but these might only be useful for some of our needs. So it is allowed to change these methods without changing the actual source code of the plugin by method overriding.

34. How does event delegation work in jQuery?

The event delegation allows us to handle events on multiple elements efficiently by not explicitly attaching the event handlers to each element individually. It takes advantage of the concept of event bubbling. To implement the event delegation in jQuery, we add an event handler to the parent element present in the DOM, which holds all the child elements. When an event occurs on a child element, it bubbles up to the parent element and eventually triggers the event handler corresponding to that parent element. This is how we can improve the performance and reduce memory usage by not assigning each element an event handler.

35. Is it possible to trigger an event using a method or a property of jQuery?

Yes, we can trigger an event by using the '.trigger()’ method. It helps us to simulate the occurrence of even on an element. To check the event handler functions in our application, we generally use triggers by using inbuilt methods instead of hardware triggers.

For Example:

$(“#navButton_id”).trigger(“mouseenter”);


Here, the ‘.trigger()’ method is triggering a ‘mouseenter’ event on the elements having an id “navbutton_id”. This will execute the event handlers associated with the ‘mouseenter’ event for the selected elements.

jQuery Coding Questions

In this section, we will discuss 10 coding questions based on jQuery coding with the answers are as follows:

36. How to change the text value of the button on the click?

<!DOCTYPE html>
<html>
   <head>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script>
         $(document).ready(function() {
           $('button').click(function() {
             $(this).text("BUTTON CLICKED!");
           });
         });
      </script>
   </head>
   <body>
      <button>CLICK HERE</button>
   </body>
</html>

 

In the above code, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, “CLICK HERE”, and if a user clicks on this button, a function will be called, and the text value of the “button” tag will be changed from “CLICK HERE” to “BUTTON CLICKED”.

37. How to retrieve the text content of the specific element with its class using jQuery?

You need to start the statement with the “$” symbol, and the element is supposed to be retrieved with its class name. If the class is passed, “." will be followed by the class name. There is a function in jquery library text() by which we can retrieve the text content, so it will be passed in the brackets like this: $(".class_name").text(). Here is the code below for a better understanding:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              $('button').click(function() {
                $('h1').text($(".para_class").text());
              });
            });
        </script>
    </head>
    <body>
        <p class="para_class" >HELLO NINJA</p>
        <button>RETRIEVE CONTENT</button>
        <h1></h1>
    </body>
</html>

 

In the above code, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, “RETRIEVE CONTENT”, and if a user clicks on this button, a function will be called, and the text value of the “p” tag with class name “para_class” will be copied to the text value of “h1” tag which will result “HELLO NINJA”.

38. How to retrieve the length of the text value of the ‘p’ tag using jQuery?

You need to start the statement with the “$” symbol, and the element is supposed to be retrieved with its ID. The length methods will be used to retrieve the length of the text, respectively, so it will be passed in the brackets like this: $("p").text().length.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              $('button').click(function() {
                $('h1').text($('p').text().length);
              });
            });
        </script>
    </head>
    <body>
        <p>HELLO NINJA, THIS IS A PARAGRAPH</p>
        <button>GET LENGTH OF ABOVE CONTENT</button>
        <h1></h1>
    </body>
</html>

 

In the above code, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, “GET LENGTH OF ABOVE LENGTH”, and if a user clicks on this button, a function will be called, and the length of the text value of the “p” tag will be copied to the text value of “h1” tag which will result “32” here.

39. How to change the content of the 'p' tag after clicking the button using jQuery?

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              $("button").click(function() {
                $("p").text("New Content");
              });
            });
        </script>
    </head>
    <body>
        <button>CLICK HERE</button>
        <p>Old Content</p>
    </body>
</html>


In the above syntax, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, “CLICK HERE”, and if a user clicks on this button, a function will be called, and the value of the ‘p' tag will be changed from “Old Content” to "New Content".

40. How to append text content to the ‘p’ tag on clicking the button using jQuery?

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              $("button").click(function() {
                $("p").append(", Coding Ninja");
              });
            });
        </script>
    </head>
    <body>
        <button>CLICK HERE</button>
        <p>Good Morning</p>
    </body>
</html>


In the above syntax, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, “CLICK HERE”, and if a user clicks on this button, a function will be called, and the value of the “p” tag will be appended from “Good Morning” to “Good Morning, Coding Ninjas”.

41. How to change the background color of ‘p’ tag on clicking a button using jQuery?

To make changes in the CSS, we need to use the .css() method by which we can manipulate the CSS styling.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              $('button').click(function() {
                $('p').css('background-color', 'red');
              });
            });
        </script>
    </head>
    <body>
        <p>THIS IS A PARAGRAPH</p>
        <button>CHANGE BACKGROUND COLOR</button>
    </body>
</html>


In the above syntax, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, "CHANGE BACKGROUND COLOR", and if a user clicks on this button, a function will be called, and the background color of the “p” tag will be changed to 'red'.

42. How to display an alert box on a button click using jQuery?

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      $('button').click(function() {
      	alert("BUTTON CLICKED");
      });
    });
  </script>
</head>
<body>
  <button>SHOW ALERT</button>
</body>
</html>


In the above syntax, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, "SHOW ALERT", and if a user clicks on this button, a function will be called, and the alert will be displayed with the text “BUTTON CLICKED” written on it.

43. How to retrieve input text value on clicking a button using jQuery?

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              $('button').click(function() {
                var inpVal = $('input').val();
                $('h1').text(inpVal);
              });
            });
        </script>
    </head>
    <body>
        <input type="text">
        <button>RETRIEVE INPUT DATA</button>
        <h1></h1>
    </body>
</html>


In the above syntax, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, "RETRIEVE INPUT DATA", and if a user clicks on this button, a function will be called, and the value of the ‘input’ tag will be copied to the ‘h1’ tag.

44. How to retrieve the width of the div on clicking a button using jQuery?

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              $('button').click(function() {
                $('.width_res').text($('div').width());
              });
            });
        </script>
    </head>
    <body>
        <div style="width: 500px; height: 100px">
            <p>THIS IS PARAGRAPH</p>
            <h1>THIS IS HEADING</h1>
        </div>
        <button>RETRIEVE WIDTH</button>
        <h1 class="width_res"></h1>
    </body>
</html>


In the above syntax, we created an HTML file and imported the jQuery library, which is mandatory to import. We created a button, "RETRIEVE WIDTH", and if a user clicks on this button, a function will be called, and the width of the ‘div’ tag will be copied to the ‘h1’ tag with class ’width_res' that will display the width result.

45. How to display the current time on the alert box using jQuery?

To retrieve the current time, we have to use the Date object, which will give us the current time. We also have to use toLocaleTimeString(), which will convert the time into a string representation.

<!DOCTYPE html>
<html>
    <head>
        <title>Display Current Time</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
              	var currentTime = new Date().toLocaleTimeString();
                alert(currentTime);
            });
        </script>
    </head>
    <body>
        <h1>CHECK ALERT FOR CURRENT TIME</h1>
    </body>
</html>


In the above syntax, we created an HTML file and imported the jQuery library, which is mandatory to import. The ready function will be called automatically when the DOM will be loaded, and the current time will be stored in the variable ‘currentTime’. Now we have created the alert box with the currentTime in it.

Frequently Asked Questions

What is the main focus of jQuery?

The main focus of jQuery is to provide an easy way to use JavaScript with the help of extensible features such as elements and methods, and this power of jQuery makes the website more interactive and attractive.

Which operating system is more compatible with jQuery?

Operating systems such as Mac, Windows, and Linux are more compatible with jQuery, and development and production can be easily done on these operating systems. jQuery is a lightweight library that makes it different from other libraries.

What is the starting point of jQuery?

There is a function $(document).ready() which is the starting point of jQuery code, and this function is executed whenever the DOM (Document Object Model) is loaded.

Is jQuery a library for client scripting?

Yes, jQuery is a library for client scripting where the part of frontend includes. jQuery is written on the top of JavaScript that directly interacts with the user (on the website).

Conclusion

In this article, we have covered the topic of jQuery Interview Questions. We have discussed all the essential questions related to jQuery from beginner to advanced level, which are asked in the interviews. This is all about the report. 

We hope this blog has helped you enhance your knowledge regarding jQuery Interview questions.

You can refer to these jQuery articles to learn more about jQuery Interview Questions.


Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, follow guided paths for placement preparations, and much more!!
Happy Learning Ninja!

Previous article
JPA Interview Questions
Next article
JSP Interview Questions and Answers
Live masterclass