document.querySelectorAll('.item').forEach(item => item.addEventListener (
'click', function () {
console.log('Hello World!')
}
))
<div class="container">
<article class="item">3</article>
<article class="item">2</article>
<article class="item">1</article>
</div>
As you can see I have container with three child element. I want to display 'Hello World!' when one of the article is pressed.
And when I press article that has 3 as content, console displays this:
When I press second article:
And when I press last article it displays only one 'Hello World!' in the console (how it must be). So it seems that this function is being repeated. And how to fix it?
I think your code is actually doing what you want but perhaps you're interpreting the number next to each console log incorrectly.
The number next to the console log entry indicates how many times that particular message has been logged within some interval of time.
If you change each of your listeners to also log data specific to each element, it will become more clear that each element's listener is only firing once.
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>StackOverflow Example</title>
</head>
<body>
<div class="container">
<article class="item">3</article>
<article class="item">2</article>
<article class="item">1</article>
</div>
<script>
window.onload = function () {
document.querySelectorAll(".item").forEach((item, index) =>
item.addEventListener("click", function () {
console.log("Hello World!", index);
})
);
};
</script>
</body>
</html>