Description:
The Jquery hasClass() method validate whethere selected elements having a specified class name or not. If selected elements has matched class name then it will return “true” else it will return “false”.
Syntax
.hasClass( className )
className | It specify the class name to search whether its present or not |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { $("#divAdd").click(function () { if ($("#divBox1").hasClass("sqBoxOdd")) { $("#divBox1").addClass("selected"); } if ($("#divBox2").hasClass("sqBoxOdd")) { $("#divBox2").addClass("selected"); } if ($("#divBox3").hasClass("sqBoxOdd")) { $("#divBox3").addClass("selected"); } if ($("#divBox4").hasClass("sqBoxOdd")) { $("#divBox4").addClass("selected"); } }); }); </script> <style type="text/css"> .selected { background-color: #ff6a00 !important; } .sqBoxOdd { display: inline-block; margin: 20px; width: 80px; height: 80px; left: 10px; top: 10px; background-color: #4CAF50; } .sqBoxEven { display: inline-block; margin: 20px; width: 80px; height: 80px; left: 10px; top: 10px; background-color: #4CAF50; } </style> </head> <body> <button style="margin: 20px;" id="divAdd">Add CSS Class</button><br /> <div id="divBox1" class="sqBoxOdd"></div> <div id="divBox2" class="sqBoxEven"></div> <div id="divBox3" class="sqBoxOdd"></div> <div id="divBox4" class="sqBoxEven"></div> </body> </html> |
Output:
On clicking “Add CSS Class” button then the “if” condition will execute and append the “selected” class to the matched div. The CSS class will append only if it receive true from the .hasClass() method.