skip to Main Content

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


  1. You can have all the classes in an array, then loop through the classes:

    let classNameArr = ['class-1', 'class-2', 'class-3', 'class-4', 'class-5', 'class-6', 'class-7', 'class-8'];
    let elementArr = [];
    
        
    classNameArr.forEach(cn => elementArr.push(document.getElementsByClassName(cn))); 
    

    Now access them in the following way:

    let el1 = elementArr[0];
    let el2 = elementArr[1];
    ....
    
    Login or Signup to reply.
  2. You can save the elements to an Object, to be able to retrieve them by name (el1elx). This can be done using a reducer function on the array of elements.

    Something like:

    createDemoElems();
    
    const elemsSaved = [...document.querySelectorAll(`[class^=class-]`)]
      .reduce( (acc, elem) => {
        const elemIndex = [...elem.classList]
          .find(cln => cln.startsWith(`class-`))
          .replace(/[^d]/g, ``);
    
        return {...acc, [`el${elemIndex}`]: elem};
      }, {});
    
    console.log(elemsSaved.el3);
    
    function createDemoElems() {
      for (let i = 0; i<11; i+=1) {
        document.body.insertAdjacentHTML(`beforeend`,
        `<div class="class-${i} somethingElse">div.class-${i}</div>`);
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search