0

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    You don't need to do this. IDs are automatically turned into `window` properties. – Barmar Dec 30 '21 at 16:05
  • 3
    Also, you shouldn't have quotes around `elements[i].getAttribute("id")` – Barmar Dec 30 '21 at 16:05
  • 3
    Why do you need to write `document.getElementById("${elements[i].getAttribute('id')}")`? Just use `elements[i]` – Barmar Dec 30 '21 at 16:08
  • 1
    @Barmar Yes, but it's not a good practice to use those. OP still should write `const content1 = document.getElementById('content1');` if they want to use a `content1` variable. (Of course, as soon as you find yourself looping over ids or enumerating ids, you shouldn't be using ids at all - use a `class` instead) – Bergi Dec 30 '21 at 16:39
  • 1
    @Bergi I agree, but we try to avoid addressing issues of style and best practices on SO. – Barmar Dec 30 '21 at 16:43
  • OPINION - I don't think there's any point to doing this. Just query for the element you need when you need it. Sure, there are some optimisations that you can make to prevent multiple queries for the same element but I wouldn't worry about it too much until performance becomes an issue. – phuzi Dec 30 '21 at 16:54

0 Answers0