-1

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?

ERJAN
  • 23,696
  • 23
  • 72
  • 146

3 Answers3

2

if( $(b).is($('#hit5'))   ){
        console.log("hit 5");
    }
 

in jquery we have .is method , I think it will helps you

saikumar
  • 1,041
  • 6
  • 10
1

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

Community
  • 1
  • 1
Manish Jangir
  • 5,329
  • 4
  • 42
  • 75
1

Do you really need to compare elements? Could you just compare the selectors instead?

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

 {
  //do something...

}



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");
    }
}
user5325596
  • 2,310
  • 4
  • 25
  • 42