Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
Is it good practise to declare all html elements with an ID as a variable automatically in a for loop at the start of your code?

I wrote this code which loops through all elements with an ID, and declares a variable with the same name as the ID refering to that element. The code works as expected and by using this at the top of my program I save a lot of time and lines in my program. However it almost seems to good to be true because I have never seen it done before.

I know using eval() is bad practise and wonder if using window[], like I do here, has the same effect. My question is if using this code is good practise or if it should be avoided?

<div id="content1"></div>
<div id="content2"></div>
<div id="content3"></div>
<div id="content4"></div>

<script>

  var elements = document.querySelectorAll("[id]");

  for (var i = 0; i < elements.length; i++){
    window['elements[i].getAttribute("id")'] = 
    document.getElementById("${elements[i].getAttribute('id')}");
  };

  content1.innerHTML = `<p>Hello World</p>`;
      
</script>
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!