0

I have two arrays: menu_items and clones, and I have two nested each() functions.

$(menu_items).each(function() {
  $(clones).each(function() {
    if ($(this).attr("href") == ...) {
        <do sth>
    }
  });
});

I want to check if href from item from second loop (clones) is equal to href from item from first loop (menu_items). Checking items from clones is easy: $(this).attr("href"). But what with first loop menu_items? $(this).$(this).attr("href")? I guess not :( Please help.

sailormoon
  • 325
  • 3
  • 19

1 Answers1

1

You can save the this reference in the outer loop to use it in the inner:

$(menu_items).each(function() {
  const outerThis = $(this);

  $(clones).each(function() {
    if ($(this).attr("href") == outerThis.attr('href')) {
        <do sth>
    }
  });
});

alternatively use the 2nd param of .each as described by CertainPerformance:

 $(menu_items).each(function(_, menuItem) {

      $(clones).each(function(_, clone) {
        if (clone.attr("href") == menuItem.attr('href')) {
            <do sth>
        }
      });
    });
Xatenev
  • 6,383
  • 3
  • 18
  • 42