Let's say I have an array of variables:
let fruits = [apple, orange, banana];
These variables target specific DOM elements
apple = document.getElementById("apple");
orange = document.getElementById("orange");
banana = document.getElementById("banana");
I also happen to have another set of variables that basically have "Rot" added to them
appleRot = document.getElementById("appleRot");
orangeRot = document.getElementById("appleRot");
bananaRot = document.getElementById("appleRot");
Is it possible to loop through the existing array and add "Rot" to each element so they target the other set of existing variables?
let fruits = [apple, orange, banana];
let fruitsRot = fruits.map((x) => x "Rot");
is something like this possible without the result being a string but an array of elements that happen to target the second set of variables?
CodePudding user response:
Almost there. Use:
const fruits = [
document.getElementById("apple"),
document.getElementById("orange"),
document.getElementById("banana"),];
const fruitsRot = fruits.map((x) =>
document.getElementById(x.id "Rot"));
CodePudding user response:
If you want to get a new element based on a known element's id, try this:
let fruits = [apple, orange, banana];
let fruitsRot = fruits.map((x) => {
const {id} = x;
const newId = id "Rot";
return document.getElementById(newId);
});
CodePudding user response:
In a classic way:
let fruits = ['apple', 'orange', 'banana'];
let fruitsRot = [];
for (let i = 0; i < fruits.length; i ) {
fruitsRot.push(fruits[i] "Rot");
}
console.log(fruitsRot)
To loop through an existing array and add "Rot" to each element, you can use a for loop and the push()
method. The for loop allows you to iterate over the elements of the array, and the push()
method allows you to add a new element to the end of the array.
Finally you can use your document.getElementById(...)
CodePudding user response:
I'd use the names in the array instead:
const fruitNames = ['apple', 'orange', 'banana'];
const fruits = fruitNames.map(fruitName => document.getElementById(fruitName));
const rottenFruits = fruitNames.map(fruitName => document.getElementById(`${fruitName}Rot`));