javascript - Getting Attr (ID) of Dynamically Added <li> Element with jQuery -


i'm having issues getting id of dynamically added list element. being added following:

$(".detail-view button").on("click", function(){     var noitems = $("ul#cart-items li").eq(0).attr("id");     var detailid = $(this).attr('id');      var ordertitle = $("#detail-"+ detailid + " span.order-title").text();     var inserttitle = $("<li><a href=\"#\" class=\"remove-item\"><img src=\"/assets/images/global/intra_remove_item_btn.png\" /></a>"+ ordertitle +"</li>").attr("id", detailid);      if(noitems == "emptycart") {         $("ul#cart-items li#emptycart").replacewith(inserttitle);         $("#lp-orderform li:even").addclass("highlight");     } else {         $(inserttitle).insertafter("ul#cart-items li:last");         $("#lp-orderform li:even").addclass("highlight");     } }); 

which updates original html following...

<ul id="cart-items">     <li id="emptycart">you have no items in cart.</li> </ul> 

and updates to...

<ul id="cart-items">     <li id="6955" class="highlight"><a href="#" class="remove-item"><img src="/assets/images/global/intra_remove_item_btn.png"></a>chicken garlic sauce</li>     <li id="6966"><a href="#" class="remove-item"><img src="/assets/images/global/intra_remove_item_btn.png"></a>hunan shrimp black bean sauce</li>     <li id="6965" class="highlight"><a href="#" class="remove-item"><img src="/assets/images/global/intra_remove_item_btn.png"></a>hunan pork black bean sauce</li> </ul> 

i'm trying id of list item when a.remove-item clicked remove list element.

$("ul#cart-items").live("click", "li a.replace-item", function(){     var removeitemid = $("li a.replace-item").attr("id");     alert(removeitemid); }); 

but seem value of "undefined". input appreciated. thank you!

update

to id of li on clicking <a> link

$("#cart-items").on("click", "a", function(){ var removeitemid = $(this).parent("li").attr('id'); alert(removeitemid); }); 

working jsfiddle

to id of clicked li use

$("#cart-items").on("click", "li", function(){ var removeitemid = $(this).attr('id'); alert(removeitemid); }); 

working jsfiddle


your li element does't have remove-item class , a hyperlink have

if want detect on li item click

    $("#cart-items").on("click", "li", function(){     var removeitemid = $(this).find('a').attr("class");     alert(removeitemid); }); 

working jsfiddle

else if want detect on a hyperlink click

    $("#cart-items").on("click", "a", function(){     var removeitemid = $(this).attr("class");     alert(removeitemid); }); 

working jsfiddle


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -