How do we use wildcard or regular expressions with a jQuery selector?

Wildcard or regular expressions can be used with jQuery selectors to match elements based on patterns in their attributes, particularly the id and class attributes. This is useful when you need to select multiple elements that share common naming patterns.

Common Wildcard Selectors

jQuery provides several attribute selectors that work like wildcards ?

[attribute^="value"] ? Selects elements where the attribute starts with the specified value

[attribute$="value"] ? Selects elements where the attribute ends with the specified value

[attribute*="value"] ? Selects elements where the attribute contains the specified value

Example

You can try to run the following code to use wildcard selectors with jQuery ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select all elements with id starting with 'sub'
            $("[id^=sub]").css("background-color", "green");
            
            // Select all elements with id ending with 'subject'
            $("[class$=subject]").css("color", "white");
            
            // Select all elements containing 'my' in their id
            $("[id*=my]").css("border", "2px solid red");
        });
    </script>
</head>
<body>
    <div id="sub1" class="javasubject">Java</div>
    <div id="sub2" class="htmlsubject">HTML</div>
    <div id="myid" class="rubysubject">Ruby</div>
    <div id="section">Section</div>
</body>
</html>

In this example ?

? Elements with ids starting with "sub" (sub1, sub2) get green background

? Elements with classes ending with "subject" get white text color

? Elements with ids containing "my" (myid) get red border

Conclusion

jQuery wildcard selectors provide a powerful way to select multiple elements based on attribute patterns, making your code more efficient when working with elements that follow naming conventions.

Updated on: 2026-03-13T18:13:45+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements