-1

I have two images and would like both to log another text. How can I control which element is used within querySelectorAll?

let elements = document.querySelectorAll('.penguin').forEach(function(elem) {
    elem.addEventListener('click', function() {
        console.log('Stackoverflow');
    });
});
.penguin {
    height: 100px;
}
<img class="penguin" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">
<img class="penguin" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">

I thought about using elem[0] but that doesn't work for me.

3
  • What do you mean by control which element is used? You can use querySelector() to just select the first one. Commented Dec 19, 2023 at 17:36
  • @Barmar so the first image should log for example Stackoverflow and the second one Hello World. Isn't that possible? Commented Dec 19, 2023 at 17:36
  • Say that in the question. It's not "controlling" anything, it's just taking different action depending on which was clicked. Commented Dec 19, 2023 at 17:38

1 Answer 1

2

You can use data attribute for different text values:

let elements = document.querySelectorAll('.penguin').forEach(function(elem) {
    elem.addEventListener('click', e => console.log(e.target.dataset.text));
});
.penguin {
    height: 100px;
}
<img class="penguin" data-text="Stackoverflow 1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">
<img class="penguin" data-text="Stackoverflow 2" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.