0

I have inner each like

$('a[id^="Page"]').each(function () {
   if ($(this).attr("id") == pageId) {
     $('[id="' + pageId + '"]"').each(function () {
       // code here
      });
  }
});

How to access the current element since this is from previous each?

Thanks!

Shiran Dror
  • 1,472
  • 1
  • 23
  • 36
Jake Manet
  • 1,174
  • 3
  • 15
  • 26

4 Answers4

0

you can use the callback's second argument to get the element like so:

 $('a[id^="Page"]').each(function (index, element) {
         if ($(element).attr("id") == pageId) {
                  $('[id="' + pageId + '"]"').each(function (j, pageElment) {
                       console.log(element);
                       console.log(pageElment);
                  });
         }
 });
Shiran Dror
  • 1,472
  • 1
  • 23
  • 36
0

First, you can use the following callback signature to eliminate the use of this:

.each(function(outerIndex, outerElement) {
    .each(function(innerIndex, innerElement) {
        // Do stuff with outerElement...
    });
});

This is more readable than using this tautology.

However, in your example there is no need to use the second each(... inside your first each(... at all since you're looking for exact id. And if you know the pageId in advance - you don't need any each(.... Instead just use the id selector:

$('#' + pageId).// Do your stuff
Bozhidar Stoyneff
  • 3,576
  • 1
  • 18
  • 28
0

this by default refers to the context that was calling the function. When you call .each on one or more elements, this will inside the function always refer to the current element.

Rudi
  • 2,987
  • 1
  • 12
  • 18
-1

Just save this to variable and than you can use it:

$('a[id^="Page"]').each(function () {
     var $that = $(this);

     if ($that.attr("id") == pageId) {
          $('[id="' + pageId + '"]"').each(function () {
              console.log($that.data('val') === $(this).data('val'));
          });
     }
});

If you have your ID as number (E.g. id="12345"), than read this

Community
  • 1
  • 1
Justinas
  • 41,402
  • 5
  • 66
  • 96