iOS Safari does not support the forEach method

I am facing an issue with my function that loads specific modules on specific pages based on body classes. Strangely, the forEach function is not working on iOS devices, particularly in Safari. I have been trying to troubleshoot this problem for some time now but I am unsure of the next steps to take. When using try/catch, I receive the following error message:

TypeError: document.getElementsByTagName("body")[0].classList.forEach is not a function. (In 'document.getElementsByTagName("body")[0].classList.forEach(function(e){var t=e;x.hasOwnProperty(t)&&new x[t]})', 'document.getElementsByTagName("body")[0].classList.forEach is undefined)

Below is the code snippet in question:

import Header from './Components/Header';
import Shelf from './Components/Shelf';

import Home from './Pages/Home';
import Category from './Pages/Category';
import Product from './Pages/Product';
import NossasLojas from './Pages/NossasLojas';
import Checkout from './Pages/Checkout';

const Routes = {
    "home": Home,
    "single-product": Product,
    "page-template-nossas-lojas": NossasLojas,
    "archive": Category,
    "woocommerce-cart": Checkout
};

export default class Pages {
    constructor(){
        new Header();
        new Shelf();

        try {
                document.getElementsByTagName("body")[0].classList.forEach(function(e){
                let pageName = e;

                if(Routes.hasOwnProperty(pageName)){
                    new Routes[pageName]();
                }
            })  
        }
        catch (err) {
            alert(err);
        }
    }
}

Any help or guidance on resolving this issue would be greatly appreciated. Thank you! :)

Answer №1

The class list is not an array, but rather an object.

If you want to work with it as an array, you can convert it using the Array.from() method like this:

Array.from(document.getElementsByTagName("body")[0].classList).forEach(item => console.log(item))

Answer №2

While Array.from is a viable option, consider using for of to avoid creating an extra array.

One advantage of utilizing for of comes when dealing with a large amount of async code since you can incorporate await with for of. Unfortunately, there is currently no async forEach available.

for (const e of document.getElementsByTagName("div")[0].classList) console.log(e);
<div class="one two three"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Ajax to transfer an image from an input form to a PHP script

I am currently working on a basic HTML page that includes an image upload form. Here is the code for the form: <input type='file' id='image_uploaded' accept='image'/> <input type='submit' id="upload_image"/ ...

Tips for transferring information from controller JavaScript to view JavaScript within AngularJS

Currently, I am working on an angularJS application where I retrieve data from a REST service within the controller. The retrieved data is then passed to the view using $scope. However, I encountered an issue when trying to use this data in my in-page Java ...

Does using the useState() hook in React automatically empty out the input fields?

Every time I update a state in my React application, it mysteriously erases the content of my inputs like checkboxes and numbers. Let me share a simple example to demonstrate this issue. import React, { useState } from "react"; export default fun ...

Iterating over an array of lists to tally the elements

I've been struggling to count the number of objects in an array using JavaScript. Below is the array I'm trying to work with: <script> var arr = [ {"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam", ...

What are some techniques for transforming text into JSON format?

Beginner inquiry: I'm struggling with manipulating text using JavaScript. Here is the text I want to transform: "5555 55:55: John: New York 6666 66:66: Jack: Los Angeles" My desired output after manipulation: [{ name:"John", address:"New York", n ...

Obtain the currently selected HTML element using tinyMCE

Within my editor, I have the ability to choose text and show it using the code below: alert(tinyMCE.activeEditor.selection.getContent({format : "html"})); The problem is that this function only returns text and not HtmlElement. This means I am unable to ...

Angular not updating the values in real time

First and foremost, I am utilizing socket.io to emit data. Data is emitted upon connection (so the website does not appear blank) as well as when certain events occur. Upon initial connection or page refresh, everything updates and functions smoothly. Howe ...

Dynamic Data Visualization using ChartJS with MySQL and PHP

I'm trying to create a line chart using chartJs that will display MySQL data. Specifically, I would like to use PHP to push the MySQL data to the chartJs. Here is an example of the MySQL table: id | page_views | visitors | month | ---------------- ...

Having trouble parsing FormData in the django backend

Greetings everyone! I hope you are all doing well. I've been working on a custom form that needs to be sent to the Django backend using an AJAX request. The challenge I'm facing is that when I wrap the form into FormData, it works fine on the fro ...

Utilizing Ajax and Jquery to dynamically adjust CSS properties, dependent on data from a specific MySQL row

I've been working on a system to automatically update a Scene Selection page whenever a new number is added to the permission table in Mysql. The PHP for the login and retrieving the number from the members table is working fine. My issue now lies wi ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

verifying if checkbox is selected using a while loop in PHP

Help Needed: I am currently trying to loop through some code, but I'm struggling with checking checkboxes using PHP. Could someone please review my code and provide guidance on what needs to be added? Any assistance would be greatly appreciated. Thank ...

How can I design an avatar image within a button similar to Facebook's style?

I'm currently working on a project that involves adding an avatar and a dropdown menu for account settings to my navigation bar. I've already created the dropdown, but I'm having trouble styling the avatar within the button. The button is ta ...

The hyperlink element has been added but is not clickable

I'm attempting to incorporate a download feature into my webpage using Greasemonkey. Despite successfully adding the new div element to the page, I am encountering an issue where the download window does not open as expected. var iDiv = document.crea ...

Error encountered with Firebase Modular SDK V9.0.0+: Issue with undefined firebase property 'apps' causing TypeError

Encountered an error while attempting to run my next.js app. Despite trying various methods, I have been unable to resolve it. The version of Firebase I am using is 9.0.1 Server Error TypeError: Cannot read property 'apps' of undefined The error ...

Guide on utilizing TypeScript interfaces or types in JavaScript functions with vscode and jsdocs

Is there a way to utilize types or interfaces to provide intellisense for entire functions or object literals, rather than just function parameters or inline @type's? For example: type TFunc = ( x: number ) => boolean; /** * @implements {TFunc} ...

Angular Translate Directive Unleashes the Power of XSS Vulnerabilities

For my project, I have chosen to utilize the 'escape' method as the sanitization strategy for handling potentially harmful content. This includes implementing the translate directive in certain areas, as well as utilizing the translate filter in ...

Ways to trigger the onclick event from different controls

I have a videojs player and a button on my html page. The videojs player supports the functionality to pause/play the video when clicked. I want to trigger this event by clicking on my button. How can I achieve this? Here is the code that I tried, but it ...

Is there a way in Rollup.js to substitute a dependency package's imported module with a local file?

I am currently working on a JavaScript project that needs to be bundled using Rollup.js. The project depends on package A, which in turn relies on package B: "mypackage" ---import--> "A" ----import----> "B" My package ...