Błąd podczas użycia foreach na elementach DOM

0

Czy może mi ktoś wytłumaczyć co robię nie tak? Mam 3 karty na stronie. Pobieram je za pomocą querySelectorAll i chce wywołać na każdym elemencie funkcję, przez użycie foreach. Dostaję taki o to błąd:

Uncaught TypeError: cards.foreach is not a function
    at HTMLInputElement.changePricing
        const toogle = document.getElementById("toogle");
        const cards = document.querySelectorAll(".card");
        console.log(cards);
        const changePricing = () => {

            if (toogle.checked) {
                console.log("is checked");
                cards.foreach(item => {
                    item.lastChild.style.display = "none";
                    item.firstChild.style.display = "auto";
                });

            } else {
                cards.foreach(item => {
                    console.log("is not checked");
                    item.lastChild.style.display = "none";
                    item.firstChild.style.display = "auto";

                });

            }

        };

        toogle.addEventListener("click", changePricing);
1

cards nie jest tablicą po której możesz iterować. Co zwraca ci
console.log(cards);

0

Pokaż działający demonstrator błędu.

0

Eh dzieci i ich zabawki czyli dynamiczne typowane języki programowania.

cards jest typu NodeList a nie Array. Tu jest kilka haków jak to rozwiązać

1

@KamilAdam: ale NodeList zawiera prototyp forEach, chyba że koleś ma prehistoryczną przeglądarkę. https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

2
hzmzp napisał(a):

@KamilAdam: ale NodeList zawiera prototyp forEach, chyba że koleś ma prehistoryczną przeglądarkę. https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

To chyba mamy odpowiedź forEach, a nie foreach :D

1 użytkowników online, w tym zalogowanych: 0, gości: 1