Rob M
Rob M

Reputation: 1031

selecting the id of a child element of a dynamically created link

I am trying to select the id of a <li> element that is being created under another dynamic element, an <a> tag. I cannot seem to get a handle on the id of <li>. The closest I've got is this:

 $("a li:first-child").attr('id');

but will only give the id of the first li, not the one that is being clicked.

Here is the script, which I have truncated, because the only the first part is important:

$.each(...
    $("#inventoryDiv").append("<ul id='invList'></ul>");                                                
    $("#invList").append("<a href='javascript:void(0);' name='invLink'><li id='" + this.inventory_id + "'>
...

and my listener is:

$("#inventoryDiv").on('click','a',function(){
    console.log($("a li:first-child").attr('id');
}

Any thoughts?

Upvotes: 0

Views: 1465

Answers (3)

$("#inventoryDiv").on('click','a',function(){
    console.log($(this).find('li').attr('id'));
});

Upvotes: 3

wirey00
wirey00

Reputation: 33661

first you need to switch the li and a tags around so your HTML will be valid

$("#invList").append("<li id='" + this.inventory_id + "'><a href='javascript:void(0);' name='invLink'>

then use .closest() to get the li's id

$("#inventoryDiv").on('click','a',function(){
    $(this).closest('li').prop('id');
});

Another issue you'll run into is that ALL your UL's are going to have the same ID - which is also invalid as ID's are supposed to be unique

Upvotes: 2

Tricky12
Tricky12

Reputation: 6822

Try this:

$("#inventoryDiv").on('click','a',function(){
    console.log($(this).find('li').prop('id'));
});

http://api.jquery.com/prop/

Upvotes: 1

Related Questions