Add/remove classes to list items by index - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:toggleClass

Description

Add/remove classes to list items by index

Demo Code

ResultView the demo in separate window

<!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>

Related Tutorials