Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent of element in jQuery each loop [duplicate]

I'm completely stumped on this. I have three elements on the page with a class of .topic-link.

<div id="parent1">
  <a href="#" class="topic-link"></a>
</div>
<div id="parent2">
  <a href="#" class="topic-link"></a>
</div>
<div id="parent3">
  <a href="#" class="topic-link"></a>
</div>

I can run $('.topic-link').eq(0).parent(); in the JS console and get the correct parent returned. But when I iterate over them I get an empty object each time.

$('.topic-link').each( () => {
  console.log($(this).parent());
});

// returns 3 empty objects 
like image 248
Andrew Jensen Avatar asked Oct 07 '16 18:10

Andrew Jensen


2 Answers

Arrow functions don't have their own this so what you have is not equivalent to

$('.topic-link').each(function () {
  console.log($(this).parent());
});

In your case this is window (or document or whatever depending on scope it is called in) which has no parent dom node

like image 126
charlietfl Avatar answered Oct 26 '22 19:10

charlietfl


From @charlietfl's answer: You're getting this behavior because arrow functions don't bind their own this.

To continue using an arrow function the workaround would be to use the 2nd argument from .each(), the value of the object/array.

Example (arguments are required since the arguments variable is also not bound):

$('.topic-link').each( (∅, value) => {
  console.log($(value).parent());
});
like image 39
Tibrogargan Avatar answered Oct 26 '22 18:10

Tibrogargan