0

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.

1 Answer 1

1

You can use event delegation - add a single click listener to the window. On click, if the target is a myclass and is not a myclass-1, toggle the target.

Use :not(.myclass-1) to exclude myclass-1.

window.addEventListener('click', (e) => {
  if (e.target.matches('[class^="myclass"]:not(.myclass-1')) {
    e.target.classList.toggle('another-class');
  }
});
.another-class {
  background-color: yellow;
}
<div class="myclass-1">one</div>
<div class="myclass-2">two</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.