0

When adding a dynamically added element, how can I get attributes for that element (when clicking on it, for example)? I figured out that I need to delegate an event, but I still can't access any of the attributes of that event.

This JSFiddle shows the issue problem: https://jsfiddle.net/wgc499n9/

$(this).data('index') comes up as 'undefined' - I think $(this) is referencing 'document' instead of .remove_link; even the event data doesn't seem to have any useful information in it. $(this).attr('id') also comes up as 'undefined'.

In the end, I just need to be able to click that remove link to remove the row it's on. How can I accomplish that? I even tried inline JS, but that caused even stranger behavior.

P.S. I also learned that my dynamically added data-index attribute is not stored in the DOM; jQuery stores it separately, so its containing element has to be accessed by using .find()...but I can't figure out how to use .find() to access the specific individual elements I need.

CJG
  • 175
  • 1
  • 10

2 Answers2

2

Use element event(e) parameter instead this:

let i = 0;
$('#add').on('click', () => {
  $('#container').append(`<div>row #${(i+1)} <a "href="#" data-index="${i}" class="remove_link">remove</a></div>`);
  i++;
})

$(document).on('click', '.remove_link', (e) => {
  //alert(JSON.stringify(e));
  alert($(e.target).data('index'));
})
.remove_link {
  color: red;
  font-size: 0.8em;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="add">Add row</button>
<div id="container"></div>

For more detail read difference b/w $(this) ans event.target.

Govind Samrow
  • 9,981
  • 13
  • 53
  • 90
  • I did see elsewhere that you're supposed to use the `target` attribute of the click event. But when I printed out the event details (using `JSON.stringify`), `target` showed up as an empty object, so I assumed it wouldn't work. :/ – CJG Jul 06 '17 at 17:34
2

In your event handler, this represent window. You have access to e.target to get the clicked element.

This should works:

$('#container').on('click', '.remove_link', (e) => {
    alert($(e.target).data('index'));
})
flocks
  • 218
  • 2
  • 13