0

I'm trying to get the ID of a <li> item.

The item is as follows:

echo ($y<$sites-1)?"<li id='" . $sit[0] ."'>":"<li id='$sit[0]' class=\"last\">";
echo "<a href=\"javascript:selectedSite();\" onClick=\"javascript:submit(1);\" onMouseOver=\"mouseAction(1)\" onMouseOut=\"mouseAction(0)\">" . $sit[1] . "</a></li>";

and this is my function:

function selectedSite()
{
    alert(/*I want the ID goes here*/);
}
1
  • 3
    You eneraly get more power / flexibility by setting the event handlers in Javascript instead of inline in the HTML Commented Dec 20, 2011 at 20:06

1 Answer 1

6

If you have to do it inline, the following will work for you:

echo "<a href=\"#\" onClick=\"selectedSite(this);submit(1);\" ...
function selectedSite(item)
{
    alert(item.parentNode.id);
}
Sign up to request clarification or add additional context in comments.

8 Comments

Sorry, but that's not correct. The code will be invoked globally (like passing a string to setTimeout) so this won't be a reference to the element clicked.
Then you must have changed something. Passing this only works from inline event handlers like onclick.
@ЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖ: The sample you provided doesn't give the ID, it points to the element itself. But if you put it just as Tim, alert(item.parentNode.id); will definitely work.
@sikas: The point of the sample was that it points to the window. If you find that it points to the element, then it must be a browser compatibility issue. I'm testing in Chrome. Where are you testing? In this updated example it catches the error thrown. Does it do the same for you?
@ЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖ: I'm seeing the results you mentioned. I'll update my answer accordingly. Strange I wasn't experiencing it before. Thanks for the catch!
|

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.