add active class onclick javascript

Today, We want to share with you add active class onclick javascript.In this post we will show you toggle active class javascript, hear for javascript add active class to current page we will give you demo and example for implement.In this post, we will learn about Dynamically addClass CSS click using jQuery with an example.

How To Add Active Class To Current Element?

add / remove active class


<div class="container">
  <ul class="nav">

CSS Code {
    color: green;

Simple jQuery

var selector = '.nav li';

$(selector).on('click', function(){

Highlight the active/current (pressed) button:


<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
.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 */
.active, .btn:hover {
  background-color: #666;
  color: white;

<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>
<div id="allProducts">
  <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>


var header = document.getElementById("allProducts");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var getcname = document.getElementsByClassName("active");
  if (getcname.length > 0) { 
    getcname[0].className = getcname[0].className.replace(" active", "");
  this.className += " active";


I hope you get an idea about add active class after page load jquery.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Also Read This 👉   jquery add active class to current menu item