skip to Main Content

I have tried creating this using a for loop with i such as :

const add0 = document.querySelector('.add0');
const add1 = document.querySelector('.add1');
const add2 = document.querySelector('.add2');
const add3 = document.querySelector('.add3');
const add4 = document.querySelector('.add4');
const add5 = document.querySelector('.add5');
const add6 = document.querySelector('.add6');

for(let i = 0; i <= 6; i++ {
    const add[i] = document.querySelector('.add' + i);
}

But it doesn’t work.

2

Answers


  1. Here is a simple for loop that will add all the document selectors into the array from which later you can access them using the index of the array. Also the loop is set to 6 iteration, do adjust it accordingly.

    const adds = [];
    for(let i = 0; i<6; i++) {
        adds.push(document.querySelector(`.add${i}`));
    }
    adds[0];
    

    We can you javascript template syntax for using js variables inside a string. Hope this resolves your issue.

    Login or Signup to reply.
  2. You almost had it. You have a typo in your for loop and you should declare your array before the loop. And, since the loop will populate the array with node lists, there’s no reason to create them ahead of time.

    let add = [];
    
    for(let i = 0; i <= 6; i++) {
        add[i] = document.querySelector('.add' + i);
    }
    
    console.log(add[0]);
    console.log(add[1]);
    console.log(add[2]);
    console.log(add[3]);
    console.log(add[4]);
    console.log(add[5]);
    console.log(add[6]);
    <div class="add0"></div>
    <span class="add1"></span>
    <p class="add2"></p>
    <section class="add3"></v>
    <article class="add4"></article>
    <aside class="add5"></aside>
    <h1 class="add6"></h1>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search