0

On my webpage, I have several elements. I would like, for each one of these elements to show a pop-up with the element's id. Unfortunately, that doesn't work as expected:

I made a jsfiddle to explain my issue: https://jsfiddle.net/7gk3aus5/ (click on the words)

HTML:

<div id='banana'>
Banana
</div>

<div id='strawberry'>
Strawberry
</div>

<div id='apple'>
Apple
</div>

Javascript:

var divs = document.getElementsByTagName('div');
for (var c=0; c<divs.length; c++) {
    var div = divs[c];
  div.onclick = function() {alert(div.id);}
}

As you can see, only 'apple' will be shown, while I would like to show 'banana', 'strawberry' or 'apple' depending on where the user has clicked.

Jpiz
  • 1

1 Answers1

0

You can use this( DOM element the listener was attached)/event.target( DOM element that was clicked).

 div.onclick = function() { 
    alert(this.id);
 }

demo

OR,

 div.onclick = function(event) { 
    alert(event.target.id);
 }
Satpal
  • 132,252
  • 13
  • 159
  • 168