jQuery addClass example

Change class name on click in jQuery

by Bhavdip Talaviya

HTML

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>
  
<div id="myDIV">
  <button class="btn">1</button>
  <button class="btn">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="btn">5</button>
</div>



</body>
</html>

CSS

.btn {
    border: none;
    outline: none;
    padding: 10px 16px;
    background-color: #f1f1f1;
    cursor: pointer;
    font-size: 18px;
}

/* Style the active class, and buttons on mouse-over */
.clicked, .btn:hover {
    background-color: #666;
    color: white;
}

JavaScript

// Add active class to the current button (highlight it)
$(".btn").click(function(){
$('.clicked').removeClass('clicked');
$(this).addClass('clicked');
});