let showHidePassword = function(selector){ let elem = document.querySelectorAll(selector); elem.forEach(item => { item.addEventListener("click", function(e){ e.preventDefault(); let target = document.getElementById(item.getAttribute("data-target")); if(target.type == "password") { target.type = "text"; item.classList.add("shown"); }else{ target.type = "password"; item.classList.remove("shown"); } }); });}
I have a code like this. It works, but if elem is not an even number, i.e. if there are 1 or 3 of them on the page. With an even number it doesn't work, because the loop goes through it twice, because of which the class is added and removed at the same time.
I tried all possible variants that I knew, but it didn't work. What is my problem?