2

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
    }
  }
}

3 Answers 3

4

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) { ... }
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't think of that. That's probably better than my answer.
2

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

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

2 Comments

Less jQuery, not more is the better answer here. Yes; this will work, but you're basically wrapping and then unwrapping the object, when all you want is the object itself.
@Retsam: Yeah, I realized that. I'll leave this here anyway.
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.