-1

I have a list of elements created dinamically. Each item has an ID. I didn't find how to get the id of each element when it is clicked.

Nothing is working out... :(

goes
  • 83
  • 1
  • 3
  • 9

4 Answers4

0

Just do this.id. Inside your handler this will be the clicked element and you can access its id as a property.

Ex:

   $(elem).click(function(){
       var id = this.id; //Here this is the DOM element and you can access its id property
       ///Do something..
   })
PSL
  • 123,204
  • 21
  • 253
  • 243
0

Assuming you are using jQuery:

$("li").click(function(){
    alert($(this).attr("id"));
});
Ivotje50
  • 518
  • 7
  • 15
0

When a click event is fired, the element that was the target of the click is stored as this inside of the jquery callback

$("li").click(function(){
 var elementClicked = this;
 var elementClickedId = this.id;
});
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

Using pure javascript you can do something like this:

<script>
function getID(a)
{
    document.getElementById("showid").innerHTML = a;
}
</script>
<li id="n1" onclick="getID(this);">Item1</li>
<li id="n2" onclick="getID(this);">Item2</li>
<li id="n3" onclick="getID(this);">Item3</li>

<div id="showid"></div>
Zword
  • 6,605
  • 3
  • 27
  • 52