Objects are equal by there reference not there values.
var obj1 = {name: 'Yousef', age: 15},
obj2 = {name: 'Yousef', age: 15};
console.log(obj1 === obj2); // The Result will be false
However, This rule doesn't seem to apply on DOM Objects:
var div1 = document.querySelector('div'),
div2 = document.querySelector('div');
console.log(div1 === div2); // The Result will be True!
Can anyone explain why?
Your first example is comparing two separate objects. Your DOM example is comparing one object to itself. querySelector doesn't create an object, it returns you a reference to the object that already exists in the DOM tree.
The equivalent to your DOM example would be this:
function findElement(element, tag) {
for (var n = 0; n < element.children.length; ++n) {
var child = element.children[n];
if (child.tag === tag) {
return child;
}
}
return null;
}
var tree = {
children: [
{
tag: "child",
name: "I'm the child element",
children: []
}
]
};
var obj1 = findElement(tree, "child");
var obj2 = findElement(tree, "child");
console.log(obj1 === obj2); // true
Because when you use querySelector you find the first and only the first DOM element which match your query.
So div1 and div2 are the same object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With