How to iterate through a loop in jQuery using 'each' function?

| | 1 min read

I have a number of affiliate links in my page. The affiliate links are generated dynamically and so, I don't know the number of affiliate links generated in the current page. I had a requirement to open all affiliate links simultaneously upon clicking on a search all link in my page. Initially, I was not aware of the jQuery each function. So, I placed all the affiliate links in a particular div and used the size function to get the number of 'a' tags inside that div and used a 'for loop' to iterate through the 'a' tags and applied the behavior. However, after that I found there is an each function in jQuery, which can be used to itereate through all the elements with a particular identity.

Suppose you have a search all link with id "search-all". If you want to trigger click on all links in the current page with class "affiliate-links" when clicking on the Search all link, see the following code.

  
    $("#search-all").click(function() {
      $(".affiliate-links").each(
        function() {
           this.click(); //triggering click to each element in the current page with class 'affiliate-links'.
        }
      );
    });
  

The above code will trigger click for all the elements in the current page with class 'affiliate-links' when clicking on the Search all link.