I am making a page that will list rows as entries are made with a remove button associated with each row. I can make the rows and include the button, but I can't seem to get .addEventListener() to bind to that button.
I've got an array that I'm looping through to populate my <div> (named "hospital"). I'm adding a _button and _span to a _row and that _row is then appended to hospital.
family.forEach(function(_member, cnt) {
var _row = document.createElement('li');
var _button = document.createElement("button");
_button.id = "remove_item_" + cnt;
var _button_text = document.createTextNode("Remove");
_button.appendChild(_button_text);
_row.appendChild(_button);
var _span = document.createElement("span");
_span.innerHTML = 'Age: ' + _member.age + ' / Relationship: ' + _member.rel + ' / Smoker? ' + _member.smoker;
_row.appendChild(_span);
hospital.appendChild(_row);
document.querySelector("#remove_item_" + cnt).addEventListener('click', function() {
console.log('Clicked remove');
}, false);
});
I read somewhere that the button had to exist before I could bind the event listener to it (and I thought I did with this code) but I'm still not able to do that. Am I at least close to doing this?
NOTE: I know I can do this with jQuery - I was asked to do this in pure JS.
hospital?_rowetc.