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 refers to the element.
The only time that element (or second argument) might be better than this
is if you pass 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><divclass="a"></div>
<div class="b"></div>
<div class="c"></div>
The
this.className
will return
undefined
, this is because when using
this
in another function as the example causes
this
to be equal to
global
object, ie 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><divclass="a"></div>
<div class="b"></div>
<div class="c"></div>
Extra
Note that this
and the second parameter (element) return 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><divclass="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><divclass="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>