JavaScript jQuery Basics Working with jQuery Collections Looping through a jQuery collection

Alexander D
Alexander D
8,522 Points

Help to understand loop and arguments

Hello there,

Simple question here. Can you help me to understand the mechanism that lies behind this loop?

$("a").each(function(index, anchor){
const $href = $(anchor).attr("href");
$(anchor).parent().append($href);
});

The HTML is the following:

  <ul id="restaurantList">
    <li><a href="http://www.datdog.com/">Dat Dog</a></li>
    <li><a href="https://portofcallnola.com/">Port of Call</a></li>
    <li><a href="https://www.arnaudsrestaurant.com/">Arnaud's</a></li>
    <li><a href="http://www.frenchquarter.com/nola/port-st-peter/4214/">Port St. Peter</a></li>
    <li><a href="http://www.mothersrestaurant.net/">Mother's</a></li>
  </ul>

I understand the end result, but when I use this variation below, I write 4 times the links next to each LI item, rather than one time only:

$("a").each(function(index, anchor){
const $href = $("a").attr("href");
$("a").parent().append($href);

});

Using the argument "anchor" makes it right. However, ("a") is the anchor, so I don't understand why when I change the syntax, the links("href") get written 4 times (1 time per looped item) instead of just once.

I also don't understand the "Index" argument. I thought it would be a "key" word, a specific command, but I changed it for any possible random word and I get the same result.

For instance, If I "conslole.log" the following, I get an organized list of elements in the console. If I change "index" to "Icecream" or "iLovePizza" I get the same organized list. Why?

$("a").each(function(index, anchor){
console.log(index, $(anchor).attr("href"));
});

Thanks!

Andrey Misikhin
Andrey Misikhin
16,529 Points
$("a").each(function(index, anchor)

$("a") returns an array of all a tags. On every iteration index placed inside first argument of the callback function and the element placed inside second argument. Names of this arguments may be any words, it doesn't matter.

$("a").parent().append($href);

I think, when you write like that, then on every loop you takes all elements a and append to them all.

const $href = $(anchor).attr("href");
$(anchor).parent().append($href);

In this situation $(anchor) is only one certain a element for every iteration. So if you want to do something only with element of current iteration, you must use $(anchor), or any other word, that you pass as second argument to the callback function.