Pieter
Pieter

Reputation: 32755

Getting the ID of an object when the object is given

I have link that calls a function when clicked:

<a href="javascript:spawnMenu(this);" id="link1">Test1</a>

To make my function work, I need access to the object so that I can perform jQuery operations like this:

alert($(objCaller).offset().left);

Since objCaller points to the object and not the object ID, this won't work. I need something like this:

alert($("a#link1").offset().left);

How can I get the object ID from objCaller?

Upvotes: 0

Views: 408

Answers (5)

Bialecki
Bialecki

Reputation: 31041

You can get the ID by doing this:

function spawnMenu (elem) {
    var id = elem.id; // elem is just a DOM node, so access it's id

    // your code here...
}

However, jQuery should also be able to wrap a DOM node, so the following should work as well:

function spawnMenu (elem) {
    elem = $(elem).get(0);

    // your code here...
}

Upvotes: 0

adamnfish
adamnfish

Reputation: 11255

It's not clear from your question what objCaller refers to. If it refers to the element itself, then $(objCaller) would work fine with jQuery.

Try your code using firebug (an extension for firefox). You can swap 'alert' for 'console.log' so you have:

console.log(objCaller);

This will help you work out exactly what is stored in objCaller (it isn't an element if $(objCaller) isn't working, as I say).

If objCaller is an element, then objCaller.id would be the way to retrieve the id.

Upvotes: 0

Todd
Todd

Reputation: 1674

Just off the top of my head: does alert($(this).offset().left); not work? Otherwise, you can get the ID via $(this).attr("id").

Upvotes: 0

Rob
Rob

Reputation: 8187

You need to do this:

<a href="javascript:;" onclick="spawnMenu(this);" id="link1">Test1</a>

You can't pass this via a javascript: url.

Upvotes: 3

tloflin
tloflin

Reputation: 4050

Doesn't this work?

objCaller.id

Upvotes: 2

Related Questions