-1

For each 'a'-tag (.arrow-class), I want to add an anchor tag of a .jump-class, but I'm stuck using the foreach and for functions. This is what I have, but the 'a'-tag gets the last value in the array:

var arr = []; $(".jump").each(function () { var id = $(this).attr('id'); arr.push(id); }); var arrayLength = arr.length; $(".arrow").each(function () { for (var i = 0; i < arrayLength; i++) { $(this).attr("href", arr[i]); } }); 

EDIT: ANSWER:

var arr = []; $(".jump").each(function () { var id = $(this).attr('id'); arr.push(id); }); var arrayLength = arr.length; for (var i = 0; i < arrayLength; i++) { $(".arrow").each(function (i) { $(this).attr("href", '#' + arr[i]); }); } 
4
  • Why are you "stuck" using for/foreach? Commented Dec 7, 2014 at 0:10
  • don't use an inner loop on the 2nd one, you're not iterating the arrows ever. use the params supplied to forEach to provide "i" Commented Dec 7, 2014 at 0:10
  • 1
    @EthanBrown: I think they mean they're "stuck" as in having trouble using them, not that they must use them. Commented Dec 7, 2014 at 0:11
  • $(this).attr("href", arr[i]); --- this statement is run multiple times for every .arrow Commented Dec 7, 2014 at 0:11

1 Answer 1

1

this is going to loop more times than you need

$(".arrow").each(function () { for (var i = 0; i < arrayLength; i++) { $(this).attr("href", arr[i]); } }); 

Instead try

$(".arrow").each(function (i,arrow) { $(arrow).attr("href", arr[i]); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

I think not, but ill check
Thanks! Works with $(".arrow").each(function (i) :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.