thanks for your support in the past years. I never wrote a post, this is my first one.
I have an old tree menu on a website that I am updating to fix some safety issues and I am trying to replace the eval() function.
I think it is a simple task, but I am stuck at this point and can’t go further.
I have these code lines:
this.parse = function(nodes, tree, id) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType != 1) {
continue;
}
if (nodes[i].tagName.toLowerCase() == "li") {
nodes[i].id = id + "-" + tree.length;
tree[tree.length] = new Array();
if (nodes[i].childNodes && this.hasUl(nodes[i].childNodes)) {
nodes[i].className = "section";
var a;
var b;
if (a = this.getA(nodes[i].childNodes)) {
a.id = nodes[i].id + "-a";
eval("document.getElementById('"+a.id+"').onclick = function() {"+"self.click('"+nodes[i].id+"');"+"}");
}
} else {
nodes[i].className = "box";
}
}
if (nodes[i].tagName.toLowerCase() == "ul") {
nodes[i].style.display = "none";
id = id + "-" + (tree.length - 1);
nodes[i].id = id + "-section";
tree = tree[tree.length - 1];
}
if (nodes[i].childNodes) {
this.parse(nodes[i].childNodes, tree, id);
}
}
}
I tried to replace the eval line
eval("document.getElementById('"+a.id+"').onclick = function(){"+"self.click('"+nodes[i].id+"');"+"}")
with this:
document.getElementById(a.id).onclick = function(){self.click(nodes[i].id)};
But if I click on one of the folder of the tree menu, i receive this error in the console
Uncaught TypeError: Cannot read properties of undefined (reading 'id') at document.getElementById.onclick
Strange thing, if I put the nodes[i].id
into a variable and try this code:
document.getElementById(a.id).onclick = function(){self.click(b)};
the error disappear, and the tree seems to works, but if I click in any folder, it opens only the last one. It seems that the function “self.click” is not assigned correctly to each folder of the tree.
Thanks in advance for the support.
Tree example:
enter image description here
Mattia Oppedisano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.