简体   繁体   中英

How can I repeat Javascript expression for elements with different class names

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, eg 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? NB 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM