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 most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

I am currently studying JavaScript. The syntax of my if statement with && appears to be accurate, however

I'm having trouble with the logic in my "Code your Own Adventure" program on Code Academy. I expect it to display "Great, come get your pizza!" when I enter PIZZA, YES, and YES as prompts, but instead it says "NO pizza for you!" I've tried using ...

Exploring location-based services using React-Redux

Seeking a deeper comprehension of redux and the react lifecycle methods. The issue I am facing involves a prop function within the componentDidMount that calls another function in redux. Within redux, I attempt to retrieve location data to set as the init ...

Executing a JavaScript function when a selection is made from a dropdown menu

I'm trying to create a searchable dropdown in the code below. When a value is selected from the dropdown, it should call a JavaScript function. However, I am facing issues with the code not working as expected. Can someone please assist me in resolvin ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Is there a specific measurement or scale for the dragging feature in jQuery UI draggables?

I'm interested in adjusting the position of my draggable element based on the distance moved by the mouse. For instance, if the scale is 1:2 and the cursor is moved 10px to the right, then the draggable should move 20px. I already have my draggable ...

What is the best way to set a value for a variable within a UI component in React?

I'm still learning the ropes with React and JavaScript. My current challenge involves declaring a temporary variable and assigning the value of companyData.name to it, as I need to gather data from two variables like companyData.name. Below is my cod ...

Running yarn build in react results in CSS modifications

When working in my local development environment, I have everything functioning as intended. However, after executing yarn build, all of my styles appear drastically different. The project was set up using create-react-app and styled with regular CSS. Bel ...

When placed within a setInterval loop, the event.clientY variable becomes inaccessible

I am working on a script to move an element around a web page, and I have encountered a problem. Whenever I try to put it in a loop using setInterval while the mouse is down and moving, I receive an error message stating 'Uncaught TypeError: Cannot re ...

Stop the Bootstrap row from automatically adjusting to the height of the tallest child column element, and instead utilize the extra space below the smaller element

My current framework is Bootstrap 5.2. I am aiming to create two columns, each with a col-md-6 class inside a row. You can visualize the layout through this image: . The challenge I'm facing is the inability to add another row with col-md-6 element ...

Placing the error message for validation in its appropriate position

My login form has a layout that looks like this: https://i.stack.imgur.com/i7rCj.png If I enter incorrect information, it displays like this: https://i.stack.imgur.com/ItNJn.png The issue is that when the error message appears, it causes the login form ...

No response headers retrieved from WebAPI

Currently, I am utilizing the ASP.NET WebApi in conjunction with a ReactJs application on the front end. In this scenario, I am working on implementing a Get method that enables file downloads from the server. My objective is to configure both the Content- ...

tips for converting objects into arrays with JavaScript

I have an object and I would like to convert it into an array const object1 = { a: { hide:true}, b:{} }; I am currently using Object.entries to perform the conversion, however, I am struggling with understanding how it should be done. Object.entries ...

How can I make my Grid items in React and Material-UI occupy the entire horizontal space without wrapping to the next row?

I am currently utilizing Material-UI within a React 16.10 project. My goal is to create a table where the left column consists of an icon, while the right column displays a label and address stacked on top of each other. I want the items in the right colum ...

Using DIV to "enclose" all the elements inside

I need assistance with my HTML code. Here is what I have: <div id="cover" on-tap="_overlayTapped" class$="{{status}}"> <form method="POST" action="/some/action"> <input required id="name" name="name" label="Your name"></input> ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

Ways to display content exclusively to logged-in users

Currently, I am working on a website and facing a challenge in displaying certain elements on the navbar only if the user is logged in. The structure of my project involves using inheritance, which means that the navbar is included in my layout.html file. ...

What are the steps to set a 404 status code in next.js when utilizing ISR with a fallback of "blocking"?

When a route does not match, what is the best way to redirect to a 404 error page and ensure that the status code is displayed as 404 in the network tab using ISR with fallback: "blocking"? ...

Backend JS error found in Joomla 3.0 Component

Currently, I am working on developing a custom Joomla 3.0 component. To begin, I started by downloading the com_hello component sample from the official Joomla documentation. However, I've encountered an issue when trying to check the checkbox in the ...