0

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!

  • Check your browser console for errors. You can't `forEach` over an *element*. Use event delegation on the container instead – CertainPerformance Mar 04 '19 at 08:47
  • the error in console is : TypeError: document.querySelector('.gobutton').forEach is not a function. (In 'document.querySelector('.gobutton').forEach(function(button) { button.onclick = function() { this.parentElement.style.color = "red"; }; })', 'document.querySelector('.gobutton').forEach' is undefined) – Alexander Marchenko Mar 04 '19 at 09:01
  • I know what the error is - like I said, you can't `forEach` over an element. You should check the console for errors *before* posting a question. – CertainPerformance Mar 04 '19 at 09:03
  • Try `document.querySelectorAll` – Adder Mar 04 '19 at 09:04
  • This error text tells me absolutely nothing. @CertainPerformance, can you please explain in human language what it means? – Alexander Marchenko Mar 04 '19 at 09:07
  • `document.querySelector` returns a single element while `document.querySelectorAll` returns an array of elements. You can foreach over an array but not over a single element. – Adder Mar 04 '19 at 09:12
  • @Adder thanks a lot! This actually worked! – Alexander Marchenko Mar 04 '19 at 09:16

0 Answers0