Reputation: 117
I am trying to get parent element's id after re-attaching click event to a list item's third a tag (Delete), after list item is added via ajax. The structure looks as follows:
<ul id="list">
<li id="list_23">
<a href="javascript:;">Title</a>
<a href="javascript:;">Edit</a> | <a href="javascript:;">Delete</a>
</li>
<ul>
The javascript is:
$('#list li').on("click", 'a:nth-child(2)', function(event) {
event.preventDefault();
id = $(this).parent().parent().attr('id');
console.log( id );
});
I am trying to get the list items id (the "list_23"), when third a link is clicked, after element is added via ajax.
Upvotes: 0
Views: 408
Reputation: 12353
That isn't the proper way to write delegated events with .on()
. Try the following instead:
$('#list').on('click', 'li a:nth-child(3)', function(event) {
event.preventDefault();
id = $(this).parent().attr('id');
console.log( id );
});
See specifically this section of the .on()
documentation for jQuery.
Edit: Updated my answer based on the li
item being the element dynamically added to the DOM.
Edit 2: The problem was the :nth-child(n)
selector is not zero index-based, rather it is one indexed based. Added working JSFiddle.
JSFiddle: http://jsfiddle.net/wyze/vTkYf/
Upvotes: 1