jquery
  1. jquery-andself

Using JQuery andSelf()

JQuery andSelf() is a useful method that allows you to add previous elements in the stack to the current set of matched elements. It is a powerful tool for manipulating the DOM and can be used in a wide variety of applications.

Syntax

The syntax for using JQuery andSelf() is as follows:

$(selector).method().andSelf()

Use

JQuery andSelf() is used to add the previous set of matched elements to the current set. This can be useful for selecting and manipulating elements in the DOM, especially when working with complex structures. It allows you to access elements that are not immediately accessible from the current context.

Example

Here is an example of using JQuery andSelf() to select and manipulate elements in the DOM:

<!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>
    .highlight {
      background-color: red;
    }
  </style>
</head>
<body>

  <div class="parent">
    <div class="child1"></div>
    <div class="child2"></div>
  </div>

  <script>
    $(function() {
      $(".child1").next().addBack().addClass("highlight");
    });
  </script>

</body>
</html>
Try Playground

In this example, we use the JQuery andSelf() method to select the sibling element of .child1 (.child2) and add .child1 to the current set of matched elements. We then apply a CSS style to the combined set of elements, giving both .child1 and .child2 a red background color.

Summary

JQuery andSelf() is a powerful method that allows you to select and manipulate elements in the DOM with ease. It is a useful tool for working with complex structures and allows you to add previous elements in the stack to the current set of matched elements. With its simple syntax and wide range of applications, it is an essential tool for any developer working with JQuery.

Published on: