Mr A
Mr A

Reputation: 1385

JQuery: Getting data from child elements

Markup:

<ul>
<li><a href="#" class="item-list" data-id="1">Link 1</a></li>
<li><a href="#" class="item-list" data-id="2">Link 2</a></li>
<li><a href="#" class="item-list" data-id="3">Link 3</a></li>
</ul>

In JQuery, i would select link 1 and it should be able to fetch the data-id of link1. I tried

$('.item-list').click(function(){
 var link = $(this);
 alert($(this).data('id'));
});

It doesn't have any result.

Oh. the list gets generated after the page is loaded. I am querying the DB to get the list. Also, it is also possible for the list to change, depending on how the user filters the dB.

Thanks.

Upvotes: 2

Views: 1214

Answers (3)

jakee
jakee

Reputation: 18556

$('ul').on('click', '.item-list', function() {
  var link = $(this);
  alert(link.attr('data-id'));
});

See if that works

Upvotes: 0

bjornruysen
bjornruysen

Reputation: 850

If the list is generated after the page is loaded, the .click binding might not work. Maybe you can try .live, like so:

$('.item-list').live('click', function(){
   var link = $(this);
   alert($(this).data('id'));
});

EDIT:

What I always seem to forget :) as of jQuery 1.7, .live() is deprecated. You should use .on() like so:

 $("body").on("click",".item-list",function(){
    var link = $(this);
    alert($(this).data('id'));
});

Upvotes: 4

user1432124
user1432124

Reputation:

use .on because live is deprecated and also put your code inside document.ready()

$(function(){  //short form of document.ready        
    $("body").on("click",".item-list",function(){
        var link = $(this);
        alert($(this).data('id'));
    });
});

Upvotes: 2

Related Questions