Universal Selector in jQuery Tutorial 🚀

beginner
25 min

Universal Selector in jQuery Tutorial 🚀

Welcome to another enlightening tutorial! Today, we'll delve into the fascinating world of Universal Selectors in jQuery 💡. Get ready to learn a powerful technique that will help you navigate and manipulate web pages with ease!

What is a Universal Selector in jQuery? 📝

A Universal Selector in jQuery, represented by *, is used to select all elements within a document. It's like a wildcard that targets any HTML tag without specifying its type 🎯.

Why use the Universal Selector? 🤔

You might wonder, "Why would I need to select all elements on a page?" Well, there are certain scenarios where it's useful to apply styles or functions to every element. For example, when you want to give a consistent margin to all paragraphs or apply a class to every image for styling purposes.

Basic Universal Selector Example 🖇️

Let's see a simple example of using the Universal Selector to change the text color of all paragraphs on a page:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Universal Selector Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <p>This is a paragraph with red text.</p> <p>This is another paragraph with blue text.</p> <script> $(document).ready(function() { // Select all paragraphs (<p>) using the Universal Selector (*) $('* p').css('color', 'green'); }); </script> </body> </html>

In this example, we've used the Universal Selector * to select all paragraphs (<p>) on the page and changed their text color to green using the css() method.

Universal Selector with Filters 🔍

You can also combine the Universal Selector with filters to select specific elements within a group. For example, if you want to target all <img> elements with a class of 'my-image', you can do it like this:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Universal Selector with Filters Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <img class="my-image" src="image1.jpg" alt="Image 1"> <img src="image2.jpg" alt="Image 2"> <img class="my-image" src="image3.jpg" alt="Image 3"> <script> $(document).ready(function() { // Select all images with class 'my-image' using the Universal Selector (*) and the :has() filter $('* :has(.my-image)').css('border', '2px solid red'); }); </script> </body> </html>

In this example, we've used the :has() filter to select all elements that contain an <img> element with a class of 'my-image'.

Quick Quiz
Question 1 of 1

What is the purpose of the Universal Selector in jQuery?

Quick Quiz
Question 1 of 1

How can you combine the Universal Selector with filters to select specific elements within a group?