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>