Search code examples
javascriptarraysloopsnested-loopsdom-traversal

Javascript for-of loop over array and pass values into for-of loop over ul


I have a ul of items that are being displayed on a page under a form.

I want a link to be added in each li on submission of the form. I have an array of links I want to have a method loop over array and loop over li, essentially setAttribute on each li, iteratively.

my code Im working with is to watch for the submission by using an action hook (bc its a wordpress site) and returning in the action hook callback function the following:

(function(){ 
var links = ['link1', 'link2', 'link3'];  
var parentList = document.querySelector('.support-list'); 
var listItems = parentList.querySelectorAll('a');  

for(var listItem of listItems){ 
    for( var link of links){ 
         listItem.href = link; 
        } 
    }
 })()

so far I can only pass in the first link, Im not iterating over the array, but I am iterating over the li.


Solution

  • Maybe it would be better to explain more your problem. However, I see that your listItems will always has the href 'link3' that is because in the inner loop you change the link 3 times and stop at the last one 'link3'.

    Maybe this is whay you want to do

    listItems.forEach(function(item,index){
     item.href = links[index % 3]; 
    //modulus is used in case you have more than three items, otherwise it is not really needed but wont cause any trouble.
    })