jquery
  1. jquery-addback

jQuery addBack()

jQuery addBack() is a useful function that adds the previous element or selector to the current set of matched elements in a chain, allowing you to include elements that were previously excluded or removed.

Syntax

The addBack() function can be used in the following ways:

$(selector).addBack()
$(element).addBack()

Use

addBack() is useful when you want to include an element or a selector that was previously removed or excluded in a chain of jQuery methods. It is also useful for chaining multiple jQuery methods together to perform more complex operations on matched elements.

Example

Here is an example of using addBack() to include the previous selector in a chain:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <style>
    .last, .last-before {
      color: blue; /* Just for visualization purposes */
    }
  </style>
</head>
<body>

  <p>Some content</p>
  <p>Another paragraph</p>
  <p>Yet another paragraph</p>

  <script>
    // Selecting the last p element on the page
    var lastParagraph = $('p:last');

    // Adding a last class to the last p element
    lastParagraph.addClass('last');

    // Including the previous p element in the chain using prev() and addBack() methods
    lastParagraph.prev().addBack().addClass('last-before');
  </script>

</body>
</html>
Try Playground

In this example, we are selecting the last p element on the page, adding a last class to it, and then including the previous p element in the chain using prev() and addBack() methods. Finally, we are adding a last-before class to both the last element and the element before it.

Summary

addBack() is a handy jQuery function that allows you to include elements that were previously excluded or removed in a chain. Its flexible syntax and ease of use make it an excellent tool for performing complex operations on matched elements. Give it a try in your next jQuery project!

Published on: