I have some divs in my code and I want to loop them checking the actual with the last one.
Why this is not working?
<div class="tarefa">1</div>
<div class="tarefa">2</div>
<div class="tarefa">3</div>
<script>
$(function() {
i = 0 ;
$('.tarefa').each(function(index) {
i++;
if($(this).css("left") == $(this).prev('.tarefa').css("left")){
alert(i);
}
});
});
</script>
This $(this).prev('.tarefa').css("left") always get undefined.
If you had included your HTML, then we could have answered much more directly. I see two potential issues with your code.
1) When comparing the first item in the .each(), there can be no .prev() so you are asking for
.css("left")on an empty jQuery object. That will be undefined at best which will probably fail the equality test, but isn’t generally a good idea.2) If all your
.tarefaobjects are not immediate siblings with no intervening objects, then$(this).prev('.tarefa')is not doing what you expect.If you check the jQuery doc for
.prev()it gets the previous sibling only if it matches that class. It doesn’t get the previous item in your jQuery object so if your .tarefa objects are not immediate siblings of each other, your code will not work as desired.You can fix your code against both issues with this version:
EDIT Later:
With the HTML you’ve put in your comment, your original code will actually work. The first pass through the
.each()will get an undefined value for the .prev() CSS value, but it will appropriately fail your comparison and your original code will actually work. I wouldn’t recommend it as this is a much safer way to do it and probably performs a little better too.