Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality of two objects

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?

like image 357
Yousef Essam Avatar asked Aug 17 '26 22:08

Yousef Essam


2 Answers

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
like image 198
T.J. Crowder Avatar answered Aug 20 '26 13:08

T.J. Crowder


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

like image 32
sheplu Avatar answered Aug 20 '26 12:08

sheplu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!