user3117081
user3117081

Reputation: 91

Javascript Compare Objects to Elements

http://jsfiddle.net/PhilFromHeck/KzSxT/

In this fiddle, you can see at line 38 in the Javascript that I've attempted to make a comparison that isn't working. I believe it because one of the variables is an Object, where the other is an Element; does anyone have any advice as to how I can can find a match between these two?

menuID[0] = document.getElementById('menuOne'); 
menuID[1] = document.getElementById('menuTwo'); 
menuID[2] = document.getElementById('menuThree'); 
menuID[3] = document.getElementById('menuFour'); 
$('.menu').mouseenter(function () {
  for (var i = 0; i < 3; i++) {
    if(menuID[i] == $(this)){
      //this condition is not met, there's an alert which will add more detail in the fiddle
    }
  }
}

Upvotes: 2

Views: 51

Answers (3)

Retsam
Retsam

Reputation: 33399

A few issues I see here:

One is simply that, in your jsfiddle, the first 4 lines of code that you list aren't running before the bottom block runs. I'm not sure why you have both an init function that you attach to window.onload and a document.ready() function; but you'll want to make sure that init runs.

Secondly; as VisioN said, I think the main issue is that you're trying to compare a jQuery wrapper around a DOM element $(this) with a DOM element (the result of getElementById). As he says, this == menuID[i] will work.

At a design level, why not simply use the id to identify the element? this.id will give you the the id; why not simply use that to determine which menu div you're looking at?

Upvotes: 0

VisioN
VisioN

Reputation: 145408

Method document.getElementById returns a DOM element an not a jQuery object. In the mouseenter event handler this refers to a DOM element as well.

So in order to compare them you shouldn't convert this to a jQuery object:

if (menuID[i] === this) { ... }

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227260

You want to use jQuery's .is() for this.

if($(this).is(menuID[i])){

Upvotes: 2

Related Questions