Search code examples
javascriptobjectcomparisoncomparison-operators

How do i compare objects using # sign in javascript


I m using a function hitTest(a,b); i give 2 objects to it. The objects correspond to some div elements with IDs on my webpage.

where the function is called:

if (hitTest($('#drawer'),$('#hit'+i)))

 {
  //do something...

}

This is the function itself

function hitTest(a, b) {
    if( $(b) == $('#hit5')   ){
        console.log("hit 5");
    }
    else if( $(b) == $('#hit4')   ){
        console.log("hit 4");
    }

    else if( $(b) == $('#hit6')   ){
        console.log("hit 6");
    }

The problem is that none of the if clauses work! How do I compare 2 objects, or their types?


Solution

  • Try the following one:

    function hitTest(a, b) {
        if( $(b)[0] === $('#hit5')[0]   ){
            console.log("hit 5");
        }
        else if( $(b)[0] === $('#hit4')[0]   ){
            console.log("hit 4");
        }
    
        else if( $(b)[0] === $('#hit6')[0]   ){
            console.log("hit 6");
        }
    

    The jQuery objects themselves are always separate objects so you have to look at the contents of the actual DOM array inside each jQuery object.

    Reference: https://stackoverflow.com/a/7475132/1029506