jess
jess

Reputation: 1207

Jquery - accessing an element is giving null

I have page a where product and its image are loaded in a table.The image is initially hidden,and onmouseover I want to display the image.The image is inside a div tag,and productname is shown as a link.In the onready function,I attach event handler to the link,

$('a').each(function()
    {
        if( $(this).attr('id').match(/prod/)) 
        {
            $(this).mouseover(display());
        }
    });

and in the eventhandler(a function called display) I am calling

function display()
{
    $('div').each(function()
    {
        if( $(this).attr('id').match(/sx/)) 
        {
            alert("hi")
        }
    });
}

But, I am getting an error $("div") is null

HTML is:

 <table>
 <tr><td><a href="link">product name</a></td>
   <td><div class='.hidden'><table><tr><td><img   src=""></img></td></tr></table></div></td></table>

Upvotes: 2

Views: 105

Answers (2)

Mutation Person
Mutation Person

Reputation: 30488

Make the display function anonymous, much like you hve done in the rest of yoru code:

$('a').each(function()
    {
        if( $(this).attr('id').match(/prod/)) 
        {
            $(this).mouseover(function() {
                $('div').each(function()
                {
                    if( $(this).attr('id').match(/sx/)) 
                    {
                        alert("hi")
                    }
                });
            });
        }
    });

EDIT:

With regard to $("div") is null can you clarify further. Can you tell me something on the following:

var obj = $("div");      //is obj null?
alert($("div").length);  //do you get a number? If so, what is it?

Upvotes: 0

jAndy
jAndy

Reputation: 235962

replace

$(this).mouseover(display());

with

$(this).mouseover(display);

Your code is executing the function display() and passes in it's return value to mouseover. But you need to pass a function reference.

Upvotes: 2

Related Questions