jQuery universal selector


The Universal Selector (*) in jQuery is one of the simplest and most powerful selectors. It selects all elements within the DOM (Document Object Model) of a webpage. This means that when you use the Universal Selector, it will apply the specified jQuery methods or CSS styles to every element in the document, regardless of its type, class, ID, or other attributes.

Syntax

$("*")

How It Works

  • When you use $(" * "), jQuery will match every single element in the DOM.
  • This selector is useful for tasks where you need to apply a style, effect, or action to all elements on a page.
  • However, since it selects every element, it can be performance-intensive if overused, especially on large documents.

Example Usage

1. Applying a CSS Style to All Elements

You can use the Universal Selector to apply a CSS style to every element on the page.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Universal Selector Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $(" * ").css("border", "1px solid red"); }); </script> </head> <body> <h1>Heading</h1> <p>Paragraph</p> <div> <p>Another paragraph inside a div.</p> <a href="#">A link</a> </div> </body> </html>

Explanation:

  • In this example, every element (<h1>, <p>, <div>, <a>) will have a red border applied to it when the document is ready.

2. Removing All Elements

You can also use the Universal Selector to remove all elements from the page.

$("*").remove();

Explanation:

  • This code will remove all elements from the DOM, effectively leaving the page blank.

3. Iterating Over All Elements

You might want to loop through all elements and perform some operation on each one.

$("*").each(function() { console.log($(this).text()); });

Explanation:

  • This code will log the text content of every element on the page to the console.

When to Use the Universal Selector

  • Debugging or Experimentation: When you want to quickly apply a change to every element to see how it affects the page.
  • Initial Setup: If you need to reset styles or apply a baseline style to all elements, the Universal Selector can be useful.
  • Global Actions: For actions that need to be applied uniformly across the entire page, such as removing all elements, adding a global class, etc.

Performance Considerations

While the Universal Selector is powerful, it can be inefficient on pages with a large number of elements, as it requires jQuery to iterate over every element in the DOM. Therefore, it’s generally best to use more specific selectors whenever possible, reserving the Universal Selector for situations where you truly need to target all elements.