I am learning DOM manipulation with JS. Using JS I am creating several divs from an array and want to call a JS function on each of them. I wrote 2 versions: version 1 for simplicity to check if it would work at all. Ant it does work. But version 2 (that I need) doesn't work. What is wrong with version 2? Can someone help me please?
Version 1:
document.addEventListener('DOMContentLoaded', function() {
const arr = ['AAA', 'BBB', 'CCC'];
arr.forEach(add_elms);
function add_elms(arr) {
// Create div
const item = document.createElement('div');
item.innerHTML = arr;
// Add button
const go = document.createElement('button');
go.setAttribute('onclick', 'this.parentElement.style.color = "red"');
go.innerHTML = 'Go';
item.append(go);
document.querySelector('#target').append(item);
};
});
Version 2:
document.addEventListener('DOMContentLoaded', function() {
const arr = ['AAA', 'BBB', 'CCC'];
arr.forEach(add_elms);
function add_elms(arr) {
// Create div
const item = document.createElement('div');
item.innerHTML = arr;
// Add button
const go = document.createElement('button');
go.className = 'gobutton';
go.innerHTML = 'Go';
item.append(go);
document.querySelector('#target').append(item);
};
document.querySelector('.gobutton').forEach(function(button) {
button.onclick = function() {
this.parentElement.style.color = "red";
};
});
Any ideas what's wrong with my Version 2? Thanks!