Udzzzz
Udzzzz

Reputation: 155

Loops are not working in internet explorer

I have simple code for toggle up and down that is working on other browser except IE, I think because I'm using forEach, but I'm not sure if that's the cause. How to fix this?

const dropWrapper = document.querySelectorAll(".dropdown");

dropWrapper.forEach(function (el) {

    let drop = el.querySelector(".dropdown-company-trust");
    let dropContainer = el.querySelector("#myDropdown");
    let arrow = el.querySelector(".jsArrow");

    drop.addEventListener("click", function () {
        dropContainer.classList.toggle("show");
        arrow.classList.toggle("jsArrowUp");
    })

})

Upvotes: 1

Views: 273

Answers (2)

tom
tom

Reputation: 10539

forEachis supported in Internet Explorer BUT not for iterating over a NodelList:

NodeList.forEach(callback[, thisArg]);

You can find the browser compatibility here

To get foreEach work in Internet Explorer use a polyfill. It sets the NodeList.foreEachequal to Array.foreEach.

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

var dropWrapper = document.querySelectorAll(".dropdown");

dropWrapper.forEach(function() {
    // ...
});

Upvotes: 2

Barmar
Barmar

Reputation: 780869

forEach isn't available for NodeList, so you can write it the old-fashioned way with a for loop.

for (let i = 0; i < dropWrapper.length; i++) {
    let el = dropWrapper[i];
    let drop = el.querySelector(".dropdown-company-trust");
    let dropContainer = el.querySelector("#myDropdown");
    let arrow = el.querySelector(".jsArrow");

    drop.addEventListener("click", function () {
        dropContainer.classList.toggle("show");
        arrow.classList.toggle("jsArrowUp");
    })
}

Upvotes: 2

Related Questions