In my program I save my elements in each variable in a classic way. But there are many lines of code when there are many elements. Is there a more efficient way to do it?
let el1 = document.getElementsByClassName('class-1');
let el2 = document.getElementsByClassName('class-2');
let el3 = document.getElementsByClassName('class-3');
let el4 = document.getElementsByClassName('class-4');
let el5 = document.getElementsByClassName('class-5');
let el6 = document.getElementsByClassName('class-6');
let el7 = document.getElementsByClassName('class-7');
let el8 = document.getElementsByClassName('class-8');
2
Answers
You can have all the classes in an array, then loop through the classes:
Now access them in the following way:
You can save the elements to an Object, to be able to retrieve them by name (
el1
…elx
). This can be done using a reducer function on the array of elements.Something like: