Avan CaiJun
Avan CaiJun

Reputation: 111

how to get the id of a dynamic list items

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

Answers (4)

rrk
rrk

Reputation: 15846

$('.list-item').click(function () {
   aler($(this).prop('id'));
});

Upvotes: 2

juju
juju

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

Andy West
Andy West

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

Arun P Johny
Arun P Johny

Reputation: 388406

There are 2 things you have to do

  1. Use a class selector to select the elements are list-item is a class not id
  2. this 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

Related Questions