Search code examples
javascriptgetattribute

No returns from a function which contains getAttribute


I am trying to display the value of the button, but nothing shows up in the console when I press the buttons.

I am missing something and I can't figure it out.

 const allButtons = document.querySelector("[data-buttons]");

    Array.from(allButtons).forEach(button => {
        button.addEventListener("click", () => {
            let userPick = button.getAttribute("[data-pick]");
            console.log(userPick);
        });
    });

Thank you! :)


Solution

  • If You have more then one button you need to use querySelectorAll

     const allButtons = document.querySelectorAll("[data-buttons]");
    
        Array.from(allButtons).forEach(button => {
            button.addEventListener("click", () => {
                let userPick = button.getAttribute("data-pick");
                console.log(userPick);
            });
        });
    <button data-buttons="1" data-pick="1"> 1</button>
    <button data-buttons="2" data-pick="2"> 2</button>
    <button data-buttons="3" data-pick="3"> 3</button>