When having a code like this:
$elements.filter(() => {
console.log(this); // will be the parent scope's "this"
});
you are not able to get the element that should be filtered. So you would need to use a normal function, like:
$elements.filter(function(){
console.log($(this)); // will be the element to filter
});
Is there any other way instead of using normal functions?
I know for click events you can use event.currentTarget, but there is no event parameter in filter.
While you don't get the reference to the expected this, it's possible to use the arguments supplied by the anonymous function, the index and the DOM node, in that order:
$elements.filter((index, node) => {
console.log(node);
});
let $elements = $('li');
$elements.filter((index, node) => {
console.log(node);
});
li {
width: 50%;
border: 2px solid #000;
}
li.red {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="red"></li>
<li class="red"></li>
<li class="red"></li>
<li class="red"></li>
<li></li>
<li class="red"></li>
<li class="red"></li>
<li></li>
<li class="red"></li>
<li></li>
<li class="red"></li>
<li class="red"></li>
<li class="red"></li>
<li class="red"></li>
<li></li>
<li></li>
<li class="red"></li>
<li class="red"></li>
<li class="red"></li>
<li></li>
<li></li>
<li></li>
</ul>
JS Fiddle demo;
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