0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
ardev
  • 653
  • 2
  • 6
  • 19
  • [Don't use `for in` enumerations on arrays](http://stackoverflow.com/q/500504/1048572). Or don't call `for of` loops `for in`? – Bergi Sep 08 '16 at 21:40
  • Sounds like you actually want `listItems[i].href = links[i]`? – Bergi Sep 08 '16 at 21:42
  • You should be setting the `href` of all the links to `link3`, since the inner loop keeps overwriting `href` of the same `listItem`. – Barmar Sep 08 '16 at 21:48
  • @4castle That comment referenced the [title of the first revision](http://stackoverflow.com/posts/39400568/revisions) – Bergi Sep 08 '16 at 22:14

2 Answers2

0

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.
})
Qaddura
  • 177
  • 6
0

When you use nested loops like that, you're setting the href of every listItem to every link. If you want to set each listItem's href to the corresponding link, you should just have a single loop where you use the same index for both collections.

for (var i = 0; i < listItems.length; i++) {
    listItems[i].href = links[i];
}
Barmar
  • 741,623
  • 53
  • 500
  • 612