Jquery Interview Questions: Part 2

Jquery Interview Questions: Part 2
Jquery Interview Questions: Part 2

Introduction

Before proceeding with the Advanced Level Jquery Interview Questions, ensure that you have completed the preliminary basic and intermediate questions for a better understanding of this topic. In our previous article, we discussed the questions for beginners and intermediates. It is now time to complete the voyage of the lingering questions to land your ideal job.

Now, let’s get started with Jquery Interview Questions:

Jquery Interview Questions

  1. How can you disable jQuery animation?

The jQuery.fx.off property is used to disable/enable all animations globally.


The default value is false, allowing animations to execute normally. When set to true, all animation techniques are disabled, which causes elements to be reset to their final state instead of showing an effect.

Syntax:-

jQuery.fx.off = true|false;

True:- Specifies that animations should be turned off.

False:- Default. Specifies whether or not animations should be enabled.

  1. What does chaining mean in jQuery?

We can use chaining to execute several jQuery methods (on the same element) within a single sentence. With jQuery chaining, you can run several methods in a single sentence. This eliminates the requirement to find the same element again to run code. It also makes the code shorter and more understandable. To use jQuery method chaining, append actions to one another.

The example below combines the css(), slideUp(), and slideDown() methods. The “p1” element initially becomes red, then slides up, then slides down:

$("#p1").css("color", "red")
  .slideUp(2000)
  .slideDown(2000);

Another example:-

blog banner 1
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $(".Ninja").css({border: "2px solid red"})
    .next().css({border:" 3px dotted yellow"});
  });
});
</script>
</head>
<body>

<p class = "Ninja"> Hi Ninja Happy learning </p>
<div>
<p>Hi Ninja Happy coding</p>
</div>
<button>Click me</button>

</body>
</html>
Output
Output after clicking on the button
  1. What is the use of animate( ) in jQuery?

The animate() function animates a series of CSS properties in a specific way.

Using CSS styles, this method changes an element from one state to another. To produce an animated effect, the CSS property value is progressively modified.

Note:- Numeric values are the only ones that can be animated (like “margin:30px”).  Except for the strings “show,” “hide,” and “toggle,” String values cannot be animated (for example, “background-colour: red”). These values enable the animated element to be hidden and shown.

Syntax:-

(selector).animate({styles},speed,easing,callback)

Styles:- Required, specifies one or more CSS properties to animate.

Note:- While using the animate() method, the property names must be camel-cased: paddingLeft should be used instead of padding-left, marginRight should be used instead of margin-right, and so on.

Speed:- Optional, specifies the speed of the animation. By default, the speed is 400 milliseconds. Possible values can be in milliseconds( like 100, 4000, 6000, etc.) or “slow” and “fast.”

Easing:- Optional, specifies the speed of the element at different portions of the animation. The default value is “swing.” The other possible value can be “linear.”

Callback:- Optional, but recommended if further processing is needed. Specifies a function to be executed after the animation completes.

For example:-

$("#box").animate({height: "300px"}, 1000, "linear");

In the above example, whoever has the id box will be picked and animated based on the characteristics provided.

  1. How to add or remove CSS classes to an element in jQuery?

To modify the CSS classes given to HTML elements, jQuery provides numerous methods such as addClass(), removeClass(), toggleClass(), and so on.

jQuery addClass( ) method:-

The jQuery addClass( ) method adds one or more classes to the selected elements.

Syntax:-

$(selector).addClass(classname,function(index,currentclass))

Classname = Required parameter, specifies one or more classes to be added. To add more than one class, separate the class name with space.

function( index, currentclass) = Optional, returns one or more class names to be added.

jQuery removeClass( ) method:-

The jQuery removeClass( ) method can remove a single class, multiple classes, or all classes at once from the selected elements.

Syntax:-

$(selector).removeClass(classname,function(index,currentclass))

Classname = Optional; it specifies one more class name to remove. To remove multiple classes, separate the class name with space.

function( index, currentclass) = Optional, it’s a function that returns one more class to remove.

jQuery toggleClass( ) method:-

The toggleClass() method adds or removes one or more classes from the selected elements. If an element already has the class, it is removed; if an element does not have the class, it is added, i.e., toggle classes.

Syntax:-

$(selector).toggleClass(classname,function(index,currentclass),switch)

Classname = Required, specifies one or more classes to be added or removed.

function( index , currentclass) = Optional, returns the class name to add/remove.

Switch = Optional, a boolean value specifying whether the class should be added( true) or removed( false).

  1. Explain what the following code does:-
$( "div" ).css( "width", "300px" ).add( "p" ).css( "background-color", "blue" );

This code employs method chaining to achieve a few tasks. It first picks all of the <div> elements and sets their CSS width to 300px. Then it adds all of the <p> elements to the current selection, allowing it to eventually modify the CSS background colour of both the < div> and <p> elements to blue.

  1. Explain the .promise( ) method in jQuery.

The .promise() method produces a dynamically generated Promise that is resolved once all actions of a given type connected to the collection, whether queued or not, have been completed.

By default, the type is “fx,” which indicates that the returned Promise is resolved after all of the animations of the specified items have finished.

For example:-

var div = $( "<div>" );
 
div.promise().done(function( arg1 ) {
  // Will fire right away and alert "true"
  alert( this === div && arg1 === div );
});
  1. What is the use of the val( ) method in jQuery?

The val() method returns or sets the value attribute of the selected elements.

When used to return a value, this method returns the FIRST matched element’s value attribute.

Syntax:-

$(selector).val()

When used to set a value, this method changes the property’s value on ALL matched elements.

Syntax:-

$(selector).val(value)

For example:-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("input:text").val("Coding Ninjas");
  });
});
</script>
</head>
<body>
<p>Name: <input type="text" name="Ninja"></p>

<button>Set the value of the input field</button>

</body>
</html>
Output
Output after clicking on the button
  1. What is the use of the serialize( ) method in jQuery?

To produce a text string in standard URL-encoded notation, use the jQuery serialize() method. It serialises the form values to utilise them in the URL query string during an AJAX request.

You have the option of selecting one or more form elements (such as input and/or text area) or the form element itself.

Syntax:-

$(selector).serialize()

For example:-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("div").text($("form").serialize());
  });
});
</script>
</head>
<body>

<form action="">
  First name: <input type="text" name="FirstName" value="Coding"><br><br>
  Last name: <input type="text" name="LastName" value="Ninjas"><br><hr>
</form>
<button style="padding:10px; font-family: cursive">Serialize form values</button><br><br>
<div></div>

</body>
</html>
Output
Output after clicking on the button
  1. What is the use of jQuery filters?

The jQuery filter is used to extract certain values from an object. It narrows down the results of your initial query to a few key items. 

For example:-

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>
Output
Output when you search for a type in the input box

We used jQuery to loop through each table row to see whether text values match the input field’s value. The toggle() method conceals the row (display: none) that does not matches the search. We utilise the toLowerCase() DOM function to convert the text to lower case, which makes the search case insensitive (allows “code,” “Code,” and even “CODE” on search).

  1. What is the use of jQuery Connect?

jQuery connect is a plugin that is used to bind or link one function to another. When a function from another object is executed, it performs a function. It’s comparable to assigning a handler to another function. 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(obj1, 'fun1', obj2, fun2);

In this case, we’re connecting the fun2 function of object 2 to the fun1 function of object 1. As a result, when fun2 is executed, fun1 is likewise executed.

  1. How to use AJAX in jQuery?

AJAX is an abbreviation for “Asynchronous JavaScript and XML.” JavaScript supports sending asynchronous HTTP requests using the XMLHttpRequest object. Ajax uses JavaScript’s ability to send asynchronous HTTP requests, get XML data as a response (also in other formats), and update a section of a web page (using JavaScript) without reloading or reloading or refreshing the entire web page.

To make an AJAX (asynchronous HTTP) request, use the ajax() method.

The ajax() function is used by all jQuery AJAX operations. This approach is typically used for requests where the previous methods are ineffective.

Syntax:

$.ajax({name:value, name:value, ... })

For example:

We have a text file named demo_test.txt, and we will see how beautifully AJAX changes the text.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url: "demo_test.txt", success: function(result){
      $("#div1").html(result);
    }});
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>
Output
Output after clicking on the button

The above code changes the text of the <div> element using the AJAX request.

  1.  What is the noConflict( ) method in jQuery?

 Many JavaScript libraries, including jQuery, utilise $ as a function or variable name. In jQuery, $ is simply an alias for jQuery; thus, all functionality is available without using $.

Run the $.noConflict() function to return control of the $ variable to the library that initially implemented it. This allows us to ensure that jQuery does not clash with other libraries’ $ objects.

Here is the simple way to avoid any Conflict:-

// Import other Library
// Import jQuery Library
$.noConflict();
// Code that uses other libraries $ can follow here.
  1.  How to check if the element is empty or not in jQuery?

 Using the “:empty”  selector, we can check if the element is empty or not.

 Syntax:-

$('Selector').is(':empty')

The element to be checked with the is() method. The is() method determines whether one of the selected elements matches the selector element.

The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty; otherwise, it returns false.

  1.  How to check if the element exists or not in the DOM?

Using jQuery.length property, we can check if the element exists or not.

If you want to fire an event only if a specific element exists in the DOM, you can use jQuery.length property to determine whether it exists or not.

The length property determines this element’s length. It determines the number of objects contained within a jQuery element. A length of 0 indicates that the element has no additional elements. Any value other than 0 indicates the presence of some element. We can use this property to check if the element exists or not. 

Syntax:-

$('Selector').length

For example:-

<script>
$(document).ready(function(){
    $("button").click(function(){
        if($("#myDiv").length){
            alert("The element you're testing is present.");
        }
      else{
         alert("The element is not present.");
      }
    });
});
</script>
<body>
    <div id="myDiv"></div>    
    <p>The quick brown fox jumps over the lazy dog</p>
    <button>Check Element</button>
</body>
output
OUTPUT
  1. Differentiate between parent( ) and parents( ) methods in jQuery.

The parent() selects one element higher up (one level higher) in the DOM tree.

The parents() method is identical to the parent() method, but it selects all matching elements up the DOM tree. It starts with the parent element and works its way up.

  • The jQuery object returned can have zero, one, or several elements.
  1.  What is the difference between the find( ) method and the children( ) method in jQuery?

Both the find() and children() methods are used to filter the child of the matched elements, with the difference being the former travels any level down while the latter only travels one level down.

To simplify:-

find() – traverse the matching elements’ children, grandchildren, great-grandchildren, and so on.

Syntax:-

$(selector).find('expression')

Expression = To filter the search for descendants, use a selection expression, element, or jQuery object.

children() – only search for the children of the matched elements (single-level down)

Syntax:-

$(selector).children(expression)

Expression = (Optional) If no filter expression is provided, it will return all direct children of the selected element. Pass the argument to filter the result.

  1. What is the finish( ) method in jQuery?

The finish() method terminates all currently running animations, eliminates all queued animations, and finishes all animations for the specified items.

This method is similar to the .stop(true, true) method, except that finish() stops all queued animations’ CSS properties.

Syntax:-

$(selector).finish(queueName)

queueName = Optional; it specifies the name of the queue to stop animations.

  1. What selector would I use to query all elements with an ID that ends with a particular string? Also, how would I modify the selector to retrieve only <div> elements whose IDs end with that exact string? Provide an example.

Let’s say you want to retrieve the element whose id ends with para. The following code could be done for the same:-

$("[id$='para']")

To retrieve only the <div> elements whose IDs end with para.

$("div[id$='para']")
  1. Write code in jQuery to animate the #expander div, expanding it from 100 x 100 pixels to 200 x 200 pixels for three seconds.

The below code is for the same:-

$( "#expander" ).animate(
  {
    width: "200px",
    height: "200px",
  },
  3000 );
  1. What is the difference between jQuery.get( ) and jQuery.ajax( ) method?

jQuery.get( ) =  The $.get() method uses an HTTP GET request to retrieve data from the server.It is simply a shortcut for $.ajax(), but it abstracts some of the setups away, establishing sensible default values for what it hides from you. The data is returned to a callback. Because it only accepts GET requests, it is supplemented by the $.post() method, which provides a similar abstraction but only for POST queries.

jQuery.ajax( ) = The most configurable is $.ajax(), which allows for fine-grained control over HTTP headers and other parameters. Using this way, you can also gain direct access to the XHR object. A slightly finer-grained error-handling system is also available. As a result, it can be more complicated and often unnecessary, yet it can also be highly valuable at times. You must handle the returned data yourself using a callback.You have complete control over the Ajax request with $.ajax(). You should utilise it if the previous ways do not meet your requirements.

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

Ajax calls can be made using the jQuery methods listed below.

  • load() : Load a snippet of HTML into a DOM container.
  • $.getJSON(): Use the GET method to load JSON.
  • $.getScript():  Load a JavaScript file.
  • $.get() is used to make a GET request and manipulate the response.
  • $.post() is used when you want to perform a POST call but don’t want to load the response into a container DOM.
  • $.ajax(): This function can be used to perform something on XHR failures or to specify ajax parameters (e.g., cache: true) on the fly. 
  1. Which of the two lines of code below is more efficient? Explain your answer.
document.getElementById( "logo" );

Or

$( "#logo" );

The first line of code is more efficient and faster because it is pure JavaScript without jQuery. So when the second line of code, jQuery, is executed, a call to the JavaScript version is made.

jQuery is built on top of JavaScript and utilises its methods behind the scenes to simplify DOM manipulation at the expense of some performance overhead. It is important to remember that jQuery is not always superior to plain old JavaScript. Always examine whether using jQuery is truly beneficial to your project.

  1. What is Event Propagation in jQuery?

The technique through which events travel through the DOM tree to their destination is known as event propagation

Let’s look at an example: imagine you’ve given a click event handler to a hyperlink (i.e. <a> element) that is contained inside a paragraph (i.e. <p> element). The handler will now be executed if you click on that link. However, if you assign the click event handler to the link’s paragraph instead of the link, clicking the link will still trigger the handler. That’s because events don’t just affect the element that triggered the event; they also traverse the DOM tree to reach their destination. This is referred to as event propagation.

There are three stages to event propagation:

Capturing Phase = The event begins at the top of the window and progresses downward until it reaches the event.target.

Target Phase = When the event has reached the event.target.

Bubbling Phase = The event bubbles up from the event.target element until it reaches the window.

three_stages
       Source: wiki

The above image demonstrates how an event travels in the DOM tree during different phases of the event propagation when an event is fired on an element with parent elements.

  1. Contrast the usage of event.preventDefault( ) and event.stopPropagation( ) in jQuery.

event.preventDefault( ):- The event.preventDefault() method prohibits an element’s default behaviour. When we utilise the form element, it prohibits the form from being submitted. When we utilise a href element, we can’t navigate. When we utilise the contextMenu element, it blocks the display.

For example:-

$("#but").click(function (event) {
  event.preventDefault()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

Output = As only the browser’s default action is blocked in the above example, the <div> click handler will trigger and display an alert message.

event.stopPropagation( ):- The event.stopPropagation  method prevents an event from propagating during the bubbling or capturing phases.

For example:-

$("#but").click(function (event) {
  event.stopPropagation()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

Output = Only the button’s click handler is called using stopPropagation, but the div’s click handler is never called.

  1. How AJAX works in jQuery?

AJAX communicates with the server using the XMLHttpRequest object.

ajax
  Source: Javascript Coder

As you can see in the preceding example, the XMLHttpRequest object is quite significant.

  • The user delivers a request through the UI, and a javascript call is sent to the XMLHttpRequest object.
  • The XMLHttpRequest object sends an HTTP request to the server.
  • JSP, PHP, Servlet, ASP.net, and other server-side languages interface with the database.
  • Data is obtained.
  • The XMLHttpRequest callback function receives XML or JSON data from the server.
  • The browser displays HTML and CSS data.

Frequently Asked Questions

What are the essential topics in jQuery?

Numerous topics are essential to crack the Interview:-

1. Cross-browser compatibility and detection
2. AJAX features
3. CSS features
4. DOM manipulation
5. Transversal Attribute Manipulation in the DOM
6. Event detection and handling
7. Animation in JavaScript
8. There are hundreds of plugins available for pre-built user interfaces, sophisticated animations, form validation, and so on
9. Custom plugins can be used to extend functionality

What is AJAX in jQuery?

AJAX is an acronym that stands for “Asynchronous JavaScript and XML.”… Ajax is about using JavaScript’s ability to send asynchronous HTTP requests, receive XML data as a response (also in other formats), and modernize a portion of a web page (using JavaScript) without reloading or refreshing the entire web page.

What is the starting point of jQuery?

The jQuery code execution begins with the $(document).ready() method whenever the entire HTML DOM is loaded and completely rendered by the browser, ensuring that the event handlers work correctly and without problems. This $(document).ready() method loads the script only after the browser has loaded the whole DOM. The starting point of jQuery code execution is the $(document).ready () function that is executed when the DOM is loaded.

Key Takeaways

To recap the conversation, we addressed the most often asked Jquery Interview questions from top-tier brands. To better understand the ideas, practise Jquery Questions as much as feasible. Practising these questions can turn you into a professional in any discipline.

This is not all. We also offer a selection of other Interview questions that will assist you in landing your ideal job. Keep an eye out for more excellent content.

Ninja, have a wonderful learning experience!

By: Alisha Chhabra