Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use wildcards like ('#name*'), ('#name%') in jQuery selectors?
For getting the id that begins or ends with a particular string in jQuery selectors, you shouldn't use the wildcards $('#name*') and $('#name%'). Instead, use the characters ^ and $ within attribute selectors. The ^ is used to get all elements starting with a particular string, while the $ is used to get all elements ending with a particular string.
These wildcards work with attribute selectors in the format [attribute^="value"] for "starts with" and [attribute$="value"] for "ends with".
Example
You can try to run the following code to learn how to get id beginning and ending with a particular string ?
<!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 elements with id ending with "new1"
$("[id$=new1]").css("background-color", "yellow");
// Select elements with id starting with "myid"
$("[id^=myid]").css("background-color", "green");
});
</script>
</head>
<body>
<div id="idnew1" myattr="javasubject">Java</div>
<div id="idnew2" myattr="htmlsubject">HTML</div>
<div id="myid1" myattr="rubysubject">Ruby</div>
<div id="myid2" myattr="cppsubject">C++</div>
</body>
</html>
In this example:
-
[id$=new1]selects elements whose id attribute ends with "new1" (matches "idnew1") -
[id^=myid]selects elements whose id attribute starts with "myid" (matches "myid1" and "myid2")
Conclusion
jQuery wildcards ^ and $ provide powerful attribute matching capabilities for selecting elements based on partial string matches, making it easy to target elements with similar naming patterns.
