Use only second argument in $.each() function in jQuery

78 Views Asked by At

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.

1

There are 1 best solutions below

1
Thomas Frank On

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)); 
});