Andrew Jensen Andrew Jensen - 1 month ago 6
Javascript Question

Get parent of element in jQuery each loop

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

Answer

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

Comments