I am currently in the process of restructuring my window.onload function to eliminate redundancy. My goal is to iterate through the elements I'm assigning to global variables using their ids. Initially, I successfully assigned onclick functions with a loop, but now I am unable to replicate this in a fiddle. The primary challenge lies in attempting to accomplish this task (view fiddle):
var gragh, gorgh;
var ids = ["gragh", "gorgh"];
for (var i = 0; i < ids.length; i++) {
ids[i] = document.getElementById(ids[i]);
// TypeError: document.getElementById(ids[i]).onclick = doStuff;
}
//console.log(gragh); undefined
The intention here is to assign the variables gragh and gorgh to p elements that share the same ids. While within the loop, ids[i] appears to reference the p elements. Yet, once outside the loop, these variables are undefined. This method also fails when iterating through an array without utilizing quotes around these variables. I even experimented with eval(), yielding mixed outcomes. Therefore, my question remains, how can I make this work? Additionally, why is this approach ineffective? Assuming ids = [gragh, gorgh] (minus the quotes), what do these variables represent within the array?