Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 16090

addEventListener does not work correctly in the loop

$
0
0
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?


Viewing all articles
Browse latest Browse all 16090

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>