-1

i wanted to turn this strings in this array to variables so i could assign them to html elements:

let array = ['varOne', 'varTwo', 'varThree']
let array[0] = document.getElementById('id')
  • 1
    This sounds to me like an X/Y problem. You are trying to achieve Y by doing X but the correct way to get Y is instead by doing Z instead of X. Can you explain to me how you are going to use the "variables" in other parts of your code? Something here does not make sense. – slebetman Jul 08 '22 at 04:29
  • like i want to use a for loop to assign each of the items in the array to that id and still use them in my code as a variable – Marvellous ajayi Jul 08 '22 at 04:35
  • So you want to assign an id, not a vairable? Like `document.body.childNodes[0].id = array[0]`? – slebetman Jul 08 '22 at 04:44
  • yeah like **array[0] = document.getElementById['id']** – Marvellous ajayi Jul 08 '22 at 18:54
  • No. I still don't get it. When you say `array[0]` you mean the string `'varOne`. So when you say `array[0] = document.getElementById('id')` you are saying you want to delete the string `varOne` and replace it with an HTML element. So if you want to delete the string `varOne` I suggest simply declare the array as `let array = [document.getElementById('id')]`. That way you don't have to create the string in the first place. – slebetman Jul 08 '22 at 23:44
  • `array[0] = document.getElementById('id')` is assigning the html element to the array. Is that what you want? You don't want to assign something to the html element but instead assign the html element to the array? – slebetman Jul 08 '22 at 23:46
  • i first want to know how to turn the strings in the array to a variable, then assign it to that html element – Marvellous ajayi Jul 09 '22 at 18:09
  • You havn't explained what you mean by "assign a variable to an element" or what the strings in the array have to do with the price of fish. You will need clarity and details if you want this question reopened to solve a problem. – traktor Jul 12 '22 at 00:19

1 Answers1

0

You almost certainly don't want to do this, but if you did here is how:

const names = ['varOne', 'varTwo', 'varThree']

names.forEach((variableName) => {
  window[variableName] = document.getElementById(variableName)
})

console.log(varOne)
console.log(varTwo)
console.log(varThree)
<html>
<body>
  <div id='varOne' />
  <div id='varTwo' />
  <div id='varThree' />
 </body>
 </html>
Asleepace
  • 3,466
  • 2
  • 23
  • 36