Javascript examples for jQuery Method and Property:toggleClass
Add/remove classes to list items by index
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("li").toggleClass(function(n){ return "myClass_" + n; });/*from w w w.j ava2s . com*/ }); }); </script> <style> .myClass_1, .myClass_3 { color: red; } .myClass_0, .myClass_2 { color: blue; } </style> </head> <body> <h1>This is a heading</h1> <ul> <li>Peter</li> <li>Lois</li> <li>Chris</li> <li>Stewie</li> </ul> <button>test</button> </body> </html>