0

I'm an amateur in JavaScript and jQuery (im a java programmer)and I'm wondering what is truly going on in the background of this comparison:

if (current == $("#hero div:last") )

I thought it would return true if they are the same object, just as would happen in Java since it would just be the same address in memory(there is only one item in the html with a class of current), but the code is not working and the condition is never met. Then I thought since multiple objects going to one var make it an Array, maybe by "current var is actually an array of size 1 so i changed it to:

if (current[0] == $("#hero div:last") )

But this did not work either. Could someone please explain what is actually going on or if i am missing the point completely? Here is the rest of the code just in case:

 $("document").ready(function(){
    setInterval("rotate()",500);
});

function rotate() {
    var current = $("#hero div.current");
    if (current == $("#hero div:last") ){
        var next = $("#hero div:first");
    }else {
        var next = current.next();
    }

    current.removeClass("current").addClass("previous");
    next.addClass("current");

}
  • 1
    Try comparing the node itself using `if (current[0] == $("#hero div:last")[0] )` – Vadorequest Jun 05 '16 at 19:48
  • The problem is because you cannot compare objects directly in JS code, for example: https://jsfiddle.net/RoryMcCrossan/bdqp75kz/. You need to find specific properties of those jQuery objects to compare against, or use `if ($current.is(':last'))` – Rory McCrossan Jun 05 '16 at 19:49
  • jQuery object is different from Javascript object, try comparing something mutual like the **ID** it will better for you now – Khaled Al-Ansari Jun 05 '16 at 19:54
  • `jQuery object is different from Javascript object` this is not the case at all. – Rory McCrossan Jun 05 '16 at 20:16
  • the code you linked to can be fixed easily by adding making it alert($div1[0] === $div2[0]); does that mean it wasnt working before because I was comparing 2 arrays? @RoryMcCrossan – Jose Medina Jun 05 '16 at 20:20
  • No, it's because you were comparing two objects. In jQuery, accessing the object by index returns a DOMElement. Therefore by doing `$div1[0] === $div2[0]` you're comparing DOMElements, which is fine. – Rory McCrossan Jun 05 '16 at 20:23

0 Answers0