Reputation: 111
I have a dynamic list of items which I want to display the details whenever a particular item is clicked.
HTML
<a id="item1" class="list-item"/>
<a id="item2" class="list-item"/>
JS
$('#list-item').click(function () {
//how do I obtain the id of the specific item?
});
So the question is how do I get the ID of the list item and do I need to declare a onclick behavior at the item's html code?
Upvotes: 0
Views: 1592
Reputation: 449
list-item is a class, not an Id so use class selector:
$('li.list-item').click (finction (){
$(this).attr ('id');//gets the I'd
});
Upvotes: 0
Reputation: 12509
$('.list-item').click(function () {
var id = $(this).attr('id');
// Do things with the ID here.
});
As noted by Arun, in your example list-item
is a class and not an id. Therefore you have to use .list-item
as a selector instead of #list-item
.
Upvotes: 1
Reputation: 388406
There are 2 things you have to do
list-item
is a class not idthis
inside the click handler will refer the clicked anchor
element so you can get its id
property to get the id//use class selector
$('.list-item').click(function() {
//Here this refers to the clicked element so
alert(this.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="item1" class="list-item">1<a/>
<a id="item2" class="list-item">2</a>
Upvotes: 2