lp chickenwigs
lp chickenwigs

Reputation: 11

Using classList on a node collection

This is the error I get using .classList.contains()

Uncaught TypeError: Cannot read property 'contains' of undefined

and please explain why it does not work: I need it for my apprenticeship

<div class="game-grid">
        <button class="covered" <?php print $array[0]?>></button>
        <button class="covered" <?php print $array[1]?>></button>
        <button class="covered" <?php print $array[2]?>></button>
        <button class="covered" <?php print $array[3]?>></button>
        <button class="covered" <?php print $array[4]?>></button>
        <button class="covered" <?php print $array[5]?>></button>
        <button class="covered" <?php print $array[6]?>></button>
        <button class="covered" <?php print $array[7]?>></button>
        <button class="covered" <?php print $array[8]?>></button>
        <button class="covered" <?php print $array[9]?>></button>
    </div>
    <script>



        let buttons = document.getElementsByClassName("covered");

        if(buttons.classList.contains("choosen") == false){

            for (button of buttons) {
                button.addEventListener("click", function(event){
                    event.target.classList.add("choosen");
                    event.target.classList.remove("covered");
                });
            }

        }     

    </script>

Upvotes: 1

Views: 250

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

getElementsByClassName returns a node collection, so you need to loop over that collection and check the n-th element .classList

Upvotes: 3

Related Questions