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 make jQuery attribute selector case insensitive?
To make jQuery attribute selector case insensitive, you need to add the case insensitive flag "i" at the end of your attribute selector. This flag makes the attribute value matching case insensitive, allowing you to match attributes regardless of their letter case.
Syntax
The basic syntax for case insensitive attribute selector is ?
$("element[attribute*='value' i]")
The i flag at the end makes the selector match attribute values in a case insensitive manner.
Example
You can try to run the following code to make jQuery attribute selector case insensitive ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Case insensitive selector - matches both 'myclass' and 'MYCLASS'
$("#insensitive").click(function(){
$("input[name*='myclass' i]").css("background-color", "yellow");
});
// Case sensitive selector - matches only exact case 'myclass'
$("#sensitive").click(function(){
$("input[name*='myclass']").css("background-color", "blue");
});
// Reset button to clear styles
$("#reset").click(function(){
$("input").css("background-color", "white");
});
});
</script>
</head>
<body>
<p>Input fields with different cases:</p>
<input name="myclass" placeholder="myclass">
<input name="MYCLASS" placeholder="MYCLASS">
<input name="MyClass" placeholder="MyClass">
<br><br>
<button id="insensitive">Case Insensitive (Yellow)</button>
<button id="sensitive">Case Sensitive (Blue)</button>
<button id="reset">Reset</button>
</body>
</html>
How It Works
In the example above ?
- The case insensitive button uses
$("input[name*='myclass' i]")which matches all input fields regardless of case - The case sensitive button uses
$("input[name*='myclass']")which only matches the exact lowercase "myclass" - The
iflag works with all attribute selector operators like*=,^=,$=, and=
Conclusion
Adding the i flag to jQuery attribute selectors makes them case insensitive, allowing you to match elements with attribute values regardless of their letter case. This is particularly useful when dealing with user-generated content or data from different sources.
