Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using this inside jQuery filter arrow function

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.

like image 234
dude Avatar asked Dec 25 '22 08:12

dude


1 Answers

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;

like image 129
David Thomas Avatar answered Jan 12 '23 06:01

David Thomas