There is no difference between the two, as described in:
Each time the callback runs, it is passed the Current loop iteration, Beginning from 0. More importantly, the callback is Fired in the context of the Current DOM element, so the keyword this refers to the element.
The only moment element (or second argument) can be better than this
is if you are going to switch to an anonymous function, for example if you do this:
$("div").each(function (i) {
setTimeout(function () {
console.log(this.className);
}, 200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
The this.className
will return undefined
, this is because when used the this
in another function as the example causes this
is equal to the object global
, or in browsers this
will be the same as the object window.
(if it is Node.js it will be the object global.
);
But if you do this will work:
$("div").each(function (i, element) {
setTimeout(function () {
console.log(element.className);
}, 200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
Extra
Note that this
and the second parameter (element) returns the DOM, but you can use any of them to manipulate with jQuery in this way:
$("div").each(function (i, element) {
var el = $(this); //ou $(element)
setTimeout(function () {
console.log(el.attr("class"));
}, 200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
You can also use the index (first parameter) to associate the index with other things, for example:
var rightList = $(".right .item");
$(".left .item").each(function (index) {
var el = $(this);
setTimeout(function () {
rightList.eq(index).text(el.text());
}, 1000 * (index + 1));
});
.left {
float: left;
}
.right {
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="left">
<div class="item">A 1</div>
<div class="item">A 2</div>
<div class="item">A 3</div>
</div>
<div class="right">
<div class="item">Vazio</div>
<div class="item">Vazio</div>
<div class="item">Vazio</div>
</div>