JavaScript code for Tree not functioning correctly on Internet Explorer

Seeking assistance to fix a bug in my JavaScript program. The code works perfectly on Google Chrome and Firefox, however it encounters an error in Internet Explorer 8 as indicated below. Any suggestions on how to resolve this issue would be greatly appreciated. Please find the link to the fiddle below:

Error Message:

SCRIPT438: Object doesn't support property or method 'keys'
File: treelist.js, Line: 12, Column: 13

Fiddle


var dataSource = {
            "Watch": {
                "Titan": {},
                "parent": {
                    "leaf1": {},
                    "leaf2": {}
                },
            }
        },
    traverseObject = function (obj) {
        var ul = document.createElement("ul"),
            li;

        for (var prop in obj) {
            li = document.createElement("li");
            li.appendChild(document.createTextNode(prop));
            li.onclick = function(e) {
                var classNames = e.currentTarget.className;
                if (classNames.indexOf("hidden") == -1) {
                    e.currentTarget.className += "hidden";
                } else {
                    e.currentTarget.className = e.currentTarget.className.replace("hidden", "");
                }
                e.stopPropagation();
            }

            if (typeof obj[prop] == "object" && Object.keys(obj[prop]).length) {
                li.appendChild(traverseObject(obj[prop]));
            } else {
                li.className += "leaf";
            }
            ul.appendChild(li);
            console.log(ul);
        }
        return ul;
    };


window.onload = function () {
    document.getElementById("dvList1").appendChild(traverseObject(dataSource));
}

Thank you

Answer №1

In IE8, the commas at the end of the members declaration are not supported.

To fix this issue, simply remove the commas like so:

 dataSource = {
        "Watch": {
            "Titan": {},
            "parent": {
                "leaf1": {},
                "leaf2": {}
            } <-- Remove this
        }

Additionally, please note that "Object.keys" is not supported in IE8:

  if (typeof obj[prop] == "object" && Object.keys(obj[prop]).length)

To address this problem, you can add the following code snippet:

if (!Object.keys) {
   Object.keys = function(obj) {
      var keys = [];

      for (var i in obj) {
         if (obj.hasOwnProperty(i)) {
            keys.push(i);
         }
      }  

      return keys;
   };
}

Answer №2

The structure of Schema can be quite complex and somewhat confusing when interpreting tree structures in JavaScript.

If you were given the opportunity to revamp it, consider creating something similar to the following:

var dataSource = {
            name : "Watch",
            nodes : [
                {
                 name : "Titan",
                 nodes: [],
                },
                {
                 name : "parent",
                 node : [
                     {
                      name : "leaf1",
                      nodes : []
                     },
                      {
                      name : "leaf2",
                      nodes : []
                      }
                 ]
                },
            ]
        };

By simplifying your code in this way, you can significantly reduce its size and eliminate any cross-browser issues without the need for workarounds.

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

What is the best way to create a promise in a basic redux action creator?

My function add does not return any promises to the caller. Here's an example: let add = (foo) => {this.props.save(foo)}; In another part of my application, I want to wait for add() to finish before moving on to something else. However, I know t ...

Tips for referencing Google Maps initialization in individual files within a website application

After setting up my Google Maps API snippet: <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script> in the index.html file, I encountered the error: Uncaught InvalidValueEr ...

The Material UI month picker interface is not displaying correctly

When trying to implement the code snippet below, <MonthPicker/> I am encountering issues with the UI of the month picker both on the website and at times. https://i.stack.imgur.com/EKsYA.png It seems like the month picker is being utilized in a di ...

What is the best way to intelligently cache specific segments of a page in PHP?

Issue: I am working on a website with over 50,000 pages, the majority of which are only updated once at the time of creation. I am in the process of implementing caching for these pages since they do not require frequent content changes. However, I am fa ...

bridging information from tables with text fields in forms

I am working on an HTML/CSS page that utilizes a table layout filled with buttons to mimic a T9 keypad design. Within the page, I have a form containing two text fields. My aim is to populate these text fields with numbers based on the values from the tab ...

Looping through an array of objects in VueJS can become a bit tricky when dealing with objects whose properties are dynamic. How can I efficiently

I am looking to create a matrix display from an array of objects, but the properties of the objects may change over time. Here is an example of the data: [ { location: "Japan", webhookStatus: "Up", authenticationStatus: &q ...

How can you utilize a computed property in a Vue component to select all the text within it?

When using $event.target.select(), I usually can select all the text. However, in this scenario, it seems to be selecting everything and then replacing the selection with the computed property. How can I select all after the computed property has finished? ...

Failed to fully install all dependencies for my project with yarn install

After cloning a project from gitlab, I attempted to install the dependencies using the yarn install command. However, there are several dependencies that yarn is unable to install and it keeps showing the error message: info There appears to be trouble wit ...

Tips for resizing a larger image to display only a specific portion in CSS (and incorporating JS if needed)

I need to resize an image that measures 1024x1024 and is segmented into 4 quadrants: My goal is to reduce the size of this image so that quadrant 2 is 256x256 while masking out or hiding the remaining 3 quadrants, displaying only the desired section on th ...

Is it possible to refresh data efficiently using web scraping tools, similar to how it

While researching web scraping in Python, I consistently found references to BeautifulSoup and Selenium as the primary tools for retrieving HTML and JavaScript content from websites. One thing that has eluded me is finding a method to automatically update ...

When attempting to initiate a new session, Webdriver.io receives an HTML response from selenium

Currently, I am attempting to execute my selenium tests using webdriver.io. However, the test runner is encountering failure when attempting to establish a session: [18:12:36] COMMAND POST "/session" [18:12:36] DATA {"desiredCapab ...

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Error: The function $scope.apply is invalid and cannot be executed

I am attempting to display the contacts list after retrieving it using rdflib.js. The data is being loaded and stored in the list within the scope. However, I am running into an issue where the $scope is not updating, and it appears that I may be calling ...

`Loading CSS files in Node.js with Express``

My CSS isn't loading properly when I run my HTML file. Even though the HTML is correctly linked to the CSS, it seems like express and node.js are not recognizing it. I find it confusing to understand the articles, tutorials, and stack overflow questio ...

Error: The function props.addToCart is not accessible

While attempting to trigger my action on the client's click of the "addToCart" button to add a new product to the cart, I encountered the error message: "TypeError: props.addToCart is not a function." I am relatively new to Redux and have grasped the ...

Challenges when working with AJAX/jQuery in terms of fetching JSON data and setting dataType

I am currently facing a challenge with my practice of AJAX/jQuery coding. Despite my efforts to learn and improve, I find the concepts of jQuery and AJAX quite perplexing. Specifically, I am struggling to understand dataTypes and how to manage different ty ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Is there a way to exit from await Promise.all once any promise has been fulfilled in Chrome version 80?

Seeking the most efficient way to determine which server will respond to a request, I initially attempted sending requests in sequence. However, desiring to expedite this probing process, I revised my code as follows: async function probing(servers) { ...

Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hov ...

Incorrect format for a date in AngularJS

I have a time input field where I am receiving the date and time format 'Thu Jan 01 1970 12:59:00 GMT+0530 (India Standard Time)', but I only want to display the time. Is there an issue with the time picker in AngularJS? Can anyone help me resolv ...