Is it possible to use $(this) and universal selector (*) with jQuery?

Yes, it is possible to use $(this) and universal selector (*) with jQuery. The universal selector selects all elements in the DOM, while $(this) refers to the current element in context. When combined, they can be used to select all elements within a specific scope.

The syntax $('*', this) selects all elements within the context of the current element, where this serves as the context parameter.

Example

You can try to run the following code to learn how to use $(this) and universal selector with jQuery ?

<!DOCTYPE html>
<html>
   <head>
      <title>jQuery Universal Selector</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {
            $('.demo1').click(function() {
               $('*', this).css("background-color", "yellow");
            });
            
            $('.demo2').click(function() {
               $('*', this).css("background-color", "lightblue");
            });
         });
      </script>
       
   </head>
   
   <body>
      <h3>Click on the divisions below:</h3>

      <div class="demo1" id="div1" style="border: 1px solid #ccc; padding: 10px; margin: 5px; cursor: pointer;">
         <p>This is first division of the DOM.</p>
         <span>Click me to change background color!</span>
      </div>

      <div class="demo2" id="div2" style="border: 1px solid #ccc; padding: 10px; margin: 5px; cursor: pointer;">
         <p>This is second division of the DOM.</p>
         <span>Click me to change background color!</span>
      </div>

   </body>
</html>

In this example, when you click on either division, the universal selector * with context this selects all child elements within that specific division and changes their background color. The first division turns elements yellow, while the second turns them light blue.

Conclusion

The combination of $(this) and the universal selector (*) provides a powerful way to select and manipulate all elements within a specific context in jQuery, making it useful for targeted styling and event handling.

Updated on: 2026-03-13T17:47:17+05:30

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements