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
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
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());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With