Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$('elems').each() with fat arrow

Tags:

I started to use ES6 fat arrow function notation and I really like it. But I am a little bit confused about it context. As far as I know, keyword this inside fat arrow function refers to context where the function is currently running. I wanted to do some simple jQuery iteration like:

$('ul#mylist > li').each(() => {    $(this).addClass('some-class-name'); }); 

But obviously this piece of code not working. How do I refer, inside fat arrow function, to current "LI" element in this specific code?

like image 322
exoslav Avatar asked Apr 11 '16 12:04

exoslav


People also ask

What is a fat arrow function?

Arrow Functions — also called “fat arrow” functions, are relatively a new way of writing concise functions in JavaScript. They have been introduced by the ECMAScript 6 specifications and since then become the most popular ES6 feature.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What does => mean in programming?

What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .


1 Answers

The each() method supplies two parameters to the callback-function. They are current index and the current item. Thus you could do the following:

$('ul#mylist > li').each((i, v) => {    $(v).addClass('some-class-name'); }); 

Where the "v" variable is the current "li" element

like image 118
Igor Bukin Avatar answered Oct 14 '22 19:10

Igor Bukin