views:

37

answers:

3

Hi guys.

A object in Javascript have a lot of properties and got this code:

var div = document.getElementsByTagName ("div");

if (div[2] === div[2]) { alert ("..."); }

There is no "id", "class", "name" or "value", so how can "div[2] === div[2]" works ? What property of the object JavaScript uses to compare ?

Thank you.

+1  A: 

It compares the unique DOM objects to each other. Every object is unique. The only way an object can equal another object is if you compare references to the same exact object.

new Object() === new Object() // false

x = new Object()
y = x

x === y // true, both variables point to the same object in memory.
meder
+1  A: 

As long as LH operand and RH operand are of same type and the reference of the objects you are comparing are the same, the value will be true for operator ===

Murali VP
Just thought I'd add that if both operands reference the same object, they by definition have the same type.
Matthew Crumley
A: 

just compare it via id

if (document.getElementById("div1") === document.getElementById("div2")){

 //do somthing

}else{

// do something

}

much safer and precise

Treby