I have multiple elements which each contain the same class name appended with a number, created dynamically depending on where in the html structure they appear, e.g. myclass-1, myclass-2, myclass-4. There could potentially (though unlikely) be unlimited class numbers.
I would like - in vanilla Javascript (no jQuery) - to add a single click function so that if the element contains any class-n except class-1 to toggle another class. I can do it individually, like this:
document.getElementById("myId").addEventListener("click", toggleClass);
function toggleClass(event){
if(event.target.classList.contains("myclass-2")){
event.target.classList.toggle("another-class");
}
}
I could repeat this code multiple times, changing "myclass-2" to "myclass-3" and so on. Is there a way to do this in one go, excluding myclass-1? N.B. I don't think it's possible to change "myclass-1" to another class name automatically on page load (or not to my limited Javascript knowledge, anyway).
If I was including "myclass-1" I could do something like this:
let existingClass = document.getElementsByClassName("*[class^=\"myclass-\"]")
But that isn't suitable here because of my need to exclude "myclass-1".
Would it be a push function? I'm very much a JS beginniner and only know the very basics of the push function, with a 'console.log' output, which doesn't help me here.
Thank you.