Top jQuery Interview Questions and Answers

author image Hirely
at 06 Jan, 2025

Question: What is the purpose of the .each() function in jQuery?

Answer:

The .each() function in jQuery is used to iterate over a jQuery object, executing a function for each matched element in the set. It allows you to perform actions on each element individually in a loop-like fashion.


Key Features of .each():

  1. Iteration:

    • .each() is used to loop through elements in a jQuery collection (e.g., all elements selected by a class or tag).
    • It executes a specified callback function once for each element in the matched set.
  2. Callback Function:

    • The callback function receives two arguments:
      • The index of the current element in the set.
      • The element itself, which is passed as a DOM element, not a jQuery object.
  3. Access to the Current Element:

    • Inside the .each() function, you can access and manipulate each element individually. The this keyword refers to the current DOM element in the iteration.
  4. Return Value:

    • .each() does not return a new jQuery object, but instead it returns the original jQuery object, allowing for chaining if needed.

Basic Syntax:

$(selector).each(function(index, element) {
  // Your logic for each element goes here
});
  • selector: The jQuery selector used to target elements.
  • function(index, element): The callback function executed for each matched element.
    • index: The index of the current element in the collection (starting from 0).
    • element: The current DOM element being processed (not wrapped in a jQuery object unless you wrap it).

Example 1: Looping Through List Items

$('li').each(function(index, element) {
  console.log('Item ' + index + ': ' + $(element).text());
});
  • This example iterates over each <li> element in the document.
  • The index represents the position of the <li> in the list, and $(element).text() logs the text of the current list item.

Example 2: Changing CSS of Each Element

$('div').each(function() {
  $(this).css('color', 'red');  // Change the text color of each <div> to red
});
  • In this example, for each <div> element, the text color is changed to red.

Example 3: Handling Multiple Elements Dynamically

$('input[type="checkbox"]').each(function() {
  if ($(this).is(':checked')) {
    $(this).closest('label').css('background-color', 'yellow');
  }
});
  • This checks each checkbox input. If it’s checked, the associated <label> element’s background color is changed to yellow.

Why Use .each()?

  • Iterate through Multiple Elements: Use .each() when you need to apply the same action to multiple elements selected by a jQuery selector.
  • Custom Logic per Element: It’s useful for custom actions that you need to perform on each element individually, like reading data, applying styles, or attaching event listeners.

Conclusion:

The .each() function is a powerful jQuery tool for iterating over collections of elements, enabling you to perform custom actions on each element in the collection. It’s essential when you need to work with multiple elements and handle them dynamically or apply specific logic to each element.

Question: How do you prevent the default action of an event in jQuery?

Answer:

In jQuery, you can prevent the default action associated with an event using the .preventDefault() method. This is particularly useful for events like form submissions, anchor clicks, or keyboard events where you want to override the browser’s default behavior.


Basic Syntax:

$(selector).on(event, function(event) {
  event.preventDefault();
});
  • event.preventDefault(): This method prevents the browser’s default behavior when the event occurs.

Common Use Cases:

  1. Preventing Form Submission:

    • If you want to prevent a form from submitting when a submit button is clicked (perhaps for client-side validation or AJAX submission):
    $('form').submit(function(event) {
      event.preventDefault();  // Prevent the form from submitting
      // Custom logic here (e.g., form validation or AJAX call)
    });
  2. Preventing Link Navigation:

    • If you want to prevent the default navigation behavior of anchor (<a>) tags, such as following a link:
    $('a').click(function(event) {
      event.preventDefault();  // Prevents navigating to the link's href
      console.log('Link clicked, but navigation is prevented');
    });
  3. Preventing Right-Click Menu (Context Menu):

    • To disable the right-click context menu in the browser:
    $(document).contextmenu(function(event) {
      event.preventDefault();  // Prevent the default context menu from appearing
      alert('Right-click is disabled.');
    });
  4. Preventing Keypress Behavior:

    • If you want to prevent the default action of a keypress (e.g., blocking certain keys like backspace or delete):
    $(document).keydown(function(event) {
      if (event.key === 'Backspace') {
        event.preventDefault();  // Prevent the backspace key from working
      }
    });

How It Works:

  • The event parameter represents the event object, which contains details about the triggered event. The .preventDefault() method is called on this object to cancel the default action.

  • For example, clicking on a link usually navigates to the URL specified in the href attribute, but calling .preventDefault() prevents this from happening, allowing you to implement your own custom logic.


Example: Preventing Form Submission with AJAX

$('#myForm').submit(function(event) {
  event.preventDefault();  // Prevent form submission
  var formData = $(this).serialize();  // Serialize form data
  $.ajax({
    url: 'submit.php',
    method: 'POST',
    data: formData,
    success: function(response) {
      console.log('Form submitted successfully');
    }
  });
});
  • This example prevents the default form submission and instead sends the form data via AJAX to the server.

Conclusion:

The .preventDefault() method in jQuery is used to stop the browser’s default behavior for certain events. It is essential for implementing custom actions, such as handling form submissions, preventing link navigation, or disabling default key behaviors.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as jQuery interview questions, jQuery interview experiences, and details about various jQuery job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now