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 OR Operation in jQuery Attribute Selectors?
Use comma to work with OR operation in jQuery Attribute Selector. The comma acts as a logical OR operator, allowing you to select elements that match any of the specified attribute combinations.
Syntax
The basic syntax for OR operation in jQuery attribute selectors is ?
$('[attribute1=value1], [attribute2=value2]')
You can also combine multiple attribute conditions with OR logic ?
$('[attr1=val1][attr2=val2], [attr1=val1][attr2=val3]')
Example
You can try to run the following code to learn how to use OR operation in jQuery attribute selector ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('[myattr=demo][myid="sub1"],[myattr=demo][myid="sub3"]').css("background-color", "yellow");
});
</script>
</head>
<body>
<div myid="sub1" myattr="demo">Java</div>
<div myid="sub2" myattr="demo">HTML</div>
<div myid="sub3" myattr="demo">Ruby</div>
</body>
</html>
The output of the above code is ?
Java (with yellow background) HTML Ruby (with yellow background)
In this example, the selector [myattr=demo][myid="sub1"],[myattr=demo][myid="sub3"] targets elements that have both myattr="demo" AND myid="sub1", OR elements that have both myattr="demo" AND myid="sub3". This results in the first and third div elements getting a yellow background.
Conclusion
The comma operator in jQuery attribute selectors provides a powerful way to implement OR logic, allowing you to select multiple elements based on different attribute combinations in a single query.
