0

Is it possible to use only the second argument of a $.each function without having to pass both arguments to use it? Let's say I have a function like this:

$('.selector').each(function(index, element){
    console.log(element);
});

But the linter doesn't like this and will throw this warning:

'index' is defined but never used.

I can just tell the linter to ignore the line, but I wanted to know if there's another way to use the second argument only, without having to declare both.

Leo
  • 956
  • 8
  • 24
  • Often an `_` is used to identify an unused argument. See: https://stackoverflow.com/a/32198002/3397771 – 76484 May 05 '23 at 16:35
  • Not in my case, the linter JSHint always complains even when adding the underscore, what I opted at the end was to use underscore for readability + the // jshint ignore:line. – Leo May 09 '23 at 14:52

1 Answers1

1

You could read all the arguments as an array using a spread and then just choose the second one (index 1). It would make your linter stop nagging, but is not that readable:

$('.selector').each(function(...args){
    console.log(args[1]);
});

However this is jQuery and you are using a traditional function (not an arrow function), so the element is available as 'this' (jQuery calls your function with the element set as this scope - which b.t.w. goes for almost all jQuery methods - event handlers etc).

// no arguments needed
$('.selector').each(function(){
    // the element as a raw HTML element
    console.log(this);
    // the element as a jQuery collection
    console.log($(this)); 
}); 
Thomas Frank
  • 1,404
  • 4
  • 10
  • The args does work in this case, but exactly not the most readable solution, but thanks for that still. For the second case I was looking really using the second parameter, as there are other functions that has different parameters and not the element as the second one. – Leo May 09 '23 at 14:44