Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery, 'this' inside function always returns document

Tags:

jquery

pug

$("#oulist li").filter(() => {
  console.log(this);
}).css("background-color", "red")

Hi, Whenever I try to use this function, this always returns as document. I am not sure whether this has something to do with pug.js.

like image 847
Pun Wai Avatar asked Mar 12 '26 10:03

Pun Wai


1 Answers

Your problem is you are using the newer ES6 arrow functions which don't use this as you would expect. Change () => { } to the traditional function() {} notation to see the difference. Read more about the arrow functions here.

You also forgot to return this; to return the <li> elements for .css();

$("#oulist li").filter(function(foo) {
  console.log(this);
  console.log("foo: " + foo); // Don't really need foo, but included.
  return this; // return <li> back to be ran with .css();
}).css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="oulist">
  <li>Foo</li>
  <li>Bar</li>
  <li>Foo</li>
  <li>Bar</li>
  <li>Foo</li>
  <li>Bar</li>
  <li>Foo</li>
</ol>
like image 170
Jimenemex Avatar answered Mar 14 '26 02:03

Jimenemex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!