I want the style to persist

The following javascript is used to click on a tab and style it with the active class. After it applies the style, it doesn’t persist. I want the tab to remain in the active state even after it has been clicked.

const tabs = document.getElementsByTagName("li");

for (const i = 0; i < tabs.length; i++) {
  tabs[i].addEventListener("click", function() {

  const current = document.getElementsByClassName("active");
  current[0].className = current[0].className.replace("active");
  this.className += "active";

  });
}

This is for an assignment so it has to be javascript and not jQuery.

What does your full project code look like? It would be easier to help if you could post all your code in Codepen and add a link here to it.

https://codepen.io/makamo66/pen/RwoQxmX

I see:

const tabs = document.getElementsByTagName("li");


for (let i = 0; i < tabs.length; i++) {
  tabs[i].addEventListener("click", function() {

  const current = document.getElementsByClassName("active");
// current[0].className = current[0].className.replace("active", "");
  current[0].className = current[0].className.replace("active");
  this.className += "active";

  });
}

You already have a function that runs each time you click on a tab (specified by the applicable callback function in each addEventListener click event. Not sure why you are also adding another click event above.

Thanks for your input, PaulOB.
I’m trying to re-factor my code so that I don’t have to hard code all of the repetitive logic. I’m not sure how to loop through the listelements for starters. This doesn’t work:

for (const i = 1; i < 5; i++) {	
    let listelement[i] = document.createElement('li');
	liststart.appendChild(listelement[i]);
	}

In your loop you used constant.
It should be something else.

I tried this:


for(const i = 1; i < 5; i++) {
  let myli = document.createElement('li');
  myli.innerHTML = "TAB "+i;
  liststart.appendChild(myli);
}

This creates TAB 1 but nothing else. It doesn’t create the second through fourth tabs.

I switched from const i = 1 to let i = 1 and now it works.

Do you understand why it is working now?
I mean the difference between const, let and var.

let can change values and const remains just the initialized value

Then my work here is done!
(dramatically flies away in general direction of the setting sun)