Search code examples
javascriptgetelementbyid

getElementById not working when I try to pass a variable into the parameter



let id = 0;
const listings = document.querySelector(".results").querySelectorAll(".item");

listings.forEach((listing) => {

        // create the button HTML
        const button = document.createElement("button");
        button.setAttribute('id',`button${id}`);
        button.setAttribute('type', 'button');

        // testing button selection
        const test = document.getElementById(`button${id}`);
        console.log(test);

        // add the button to the specified div
        const div = listing.querySelector(".specific-div");
        div.appendChild(button);

        // increment id value
        id++;
    });

I am trying to add an onClick to the buttons that I create and thus I need to select them by ID. If I go to the JS console and type something like document.getElementById("button1") the console will return the correct button element. If I go into my code and change the variable to just a specific value, i.e

const test = document.getElementById("1");
console.log(test);

I also get the correct value returned. So the issue only arises when I do getElementById(some_variable). I tried using just the id without the template string and it does not work either. querySelector doesn't work too, so I assume its a problem with the way I am implementing it not the method.


Solution

  • document.getElementById searches the document for the element with that ID.

    You've created an element and given it that id, but you haven't added it to the document (with div.appendChild(button);) yet, so when you search for it there, it isn't found.