Reputation: 21377
Suppose the following HTML:
<li class="fooli">
<a class="foo" href="javascript:foo(this);">anchor</a>
</li>
<li class="fooli">
<a class="foo" href="javascript:foo(this);">anchor</a>
</li>
and the following Javascript (using jquery 1.3.2):
function foo(anchor) {
alert($(anchor).attr('href'));
}
My goal is to be able to hide the li that is clicked on, but I can't assign them unique ids. Thus, I want to do it positionally (i.e. identify the particular anchor clicked on) by something like $(anchor).parent().hide().
However, the alert above returns "undefined", so it's not obvious to me that I even have the right jquery object.
How do I figure out what object $(anchor) is? In particular, how do I see what attributes it has, what class it has, what HTML element it is, etc?
Upvotes: 8
Views: 32466
Reputation: 48536
$(...)
in jQuery is never a single HTML element; it's always a list of them.
You can use .get()
to convert to a regular Javascript list or, better, use .each()
:
$(anchor).each(function() { alert(this) });
This will give you something like [object HTMLAElement]
. You'd have to use for/in
to examine it entirely, but .tagName
and .innerHTML
are probably good enough to figure out where you are.
I also like to use $(...).css('outline', '1px solid lime')
to find elements. It makes them hard to miss and easy to pinpoint with Firebug.
Addendum: I definitely agree with the above answer about separating your Javascript from your HTML. Don't inline JS.
Upvotes: 6
Reputation: 625027
Can't you do this:
$(function() {
$("a.foo").click(function() {
$(this).parent().hide();
return false;
});
});
with:
<li class="fooli"><a class="foo" href="#">anchor</a></li>
<li class="fooli"><a class="foo" href="#">anchor</a></li>
Upvotes: 26