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... :(
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... :(
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..
})
Assuming you are using jQuery:
$("li").click(function(){
alert($(this).attr("id"));
});
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;
});
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>