<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.
document.querySelectorAll('.item').forEach(item => item.addEventListener (
'click', function () {
console.log('Hello World!')
}
))
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?
CodePudding user response:
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>
CodePudding user response:
Change your id's to classes:
<div class="container">
<article class="item">3</article>
<article class="item">2</article>
<article class="item">1</article>
</div>
Then update the query selector:
document.querySelectorAll('.item').forEach(item => item.addEventListener (
'click', function () {
console.log('Hello World!')
}
));
ID's must be unique like in the comment by wazz.
CodePudding user response:
HTML id's must be unique. You can use class instead.
Click run code snippet below to see, It works fine now.
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>