Javascript Creating Variables And Assigning Them A Value Using A Loop
Solution 1:
Instead of handcoding posOne to posEleven or whatever you need iterate but changing number strings to digits:
var position = 1;
var totalPositions=11;
var backButton = document.getElementById("theBackButton");
var nextButton = document.getElementById("theNextButton");
var introPos = document.getElementById("introductionText");
var totalPositions=11;
var pos=[];
for (i=1; i<=totalPositions; i++) {
pos[i] = 'pos'+i+'= document.getElementById("position'+i+'")';
}
console.log(pos);
Need to change your DOM elements id, say div ids or whatever you are going to manipulate.
Keep aqn eye on the console.log, maybe eliminate after you don't need anymore.
Solution 2:
var positions = newObject();
var arrIds = ["positionOne","positionTwo","positionThree","positionFour","positionN"]
for (var position in arrIds){
var id = arrIds[position];
positions[id] = document.getElementById(id);
}
console.log(positions["positionOne"])
Solution 3:
Perhaps don't rely so much on IDs, but use general classes or selectors to find your positions, using document.getElementsByClassName('position');.
Solution 4:
One approach you might consider, is that you could assign the elements of interest a specific class in your markup. Then, get all elements of that class to an array that you could then loop through:
var elements = document.getElementsByClassName("yourClassName");
elements.forEach(function(element) {
// do things to element
});
Solution 5:
You could make two pretty collections from it as arrays:
var buttons = ["theBackButton","theNextButton","introductionText", ... ];
var positions = [];
for(var button in buttons) {
positions.push(document.getElementById(buttons[button]));
}
Now you do not have to use single variables. It depends on what you are going to achieve using a class like in other answers suggested may also be suitable.
Post a Comment for "Javascript Creating Variables And Assigning Them A Value Using A Loop"