jQuery addClass
Here is a simple example showing usage of jQuery addClass() method. jQuery version used in example is 3.2.1.
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 |
<html> <head> <!-- import jQuery library --> <script type="text/javascript" src="https://www.journaldev.com/987/jquery-3.2.1.min.js"></script> <!-- jQuery functions for addClass example --> <script type="text/javascript"> $(function() { $("p:last").addClass("selected highlight"); }); $(function() { $("p:first").addClass("highlight"); }); </script> <style> p { margin: 10px; font-size: 16px; } .selected { color: maroon; } .highlight { background: yellow; } </style> </head> <body> <p>Pankaj</p> <p>Kumar</p> <p>Bye</p> </body> </html> |
In jQuery addClass function, we are adding classes “selected” and “highlight” to the element p:last
.
Similarly we are adding class “highlight” to p:first
. So when page loads, these classes are applied to the <p> first and last child and html is formatted.
The below image shows the jQuery addClass example HTML page output in browser.
jQuery addClass example for zebra stripes effect
We are using jQuery addClass() method to create zebra stripes effect in HTML table. The html code is given below.
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 60 61 62 63 64 65 66 67 68 69 70 71 |
<html> <head> <title>jQuery addClass Example - Table Zebra Stripes</title> </head> <script type="text/javascript" src="https://www.journaldev.com/987/jquery-3.2.1.min.js"></script> <!-- jQuery script to check if row is even, addClass is used to add CSS class to the row --> <script type="text/javascript"> $(function() { $("table tr:nth-child(even)").addClass("striped"); }); </script> <!-- Below CSS is used for configuring table display --> <style type="text/css"> body,td { font-size: 12px; } table { background-color: black; border: 1px black solid; border-collapse: collapse; } th { border: 1px outset silver; background-color: blue; color: white; } tr { border: 1px outset silver; background-color: white; margin: 1px; } tr.striped { border: 1px outset silver; background-color: yellow; } td { padding: 1px 10px; } </style> <body> <table> <tr> <th>ID</th> <th>Name</th> <th>Role</th> </tr> <tr> <td>1</td> <td>Pankaj</td> <td>CEO</td> </tr> <tr> <td>2</td> <td>Lisa</td> <td>Manager</td> </tr> <tr> <td>3</td> <td>Robin</td> <td>Support</td> </tr> <tr> <td>4</td> <td>David</td> <td>Editor</td> </tr> </table> </body> </html> |
Below image shows the jQuery addClass zebra effect output in browser.
jquery-addClass-table-zebra-stripes
In above html, we are adding “striped” class to every even child of the table row using condition table tr:nth-child(even)
dynamically. That’s all about jQuery addClass method.