views:

62

answers:

4

If I do this-

alert(anchor);

I get this-

"[object HTMLLIElement]"

... ok, yep, it is the element I want. So I want to get that elements ID.

So I test it like this:

alert(anchor.attr("id"));

... but I don't get any alert, nothing. I must not be selecting an element. What am I doing wrong, what don't I understand?

+3  A: 

That's because attr is not a defined method or property on anchor. anchor is a raw HTML element object. It's not a jQuery object (I'm assuming you're using jQuery because you used the attr method).

To get the id, all you have to do is anchor.id. If you really want to use attr, you can do jQuery(anchor).attr("id").

Vivin Paliath
+2  A: 

The attr() function is part of jQuery, but you're trying to get it from a plain DOM object. You either want to use $(anchor) (to wrap the element in jQuery) or call anchor.getAttribute("id") instead.

Chuck
or rather: `anchor.id`.
Marcel Korpel
+3  A: 

if you are using jquery, then you need this:

alert($(anchor).attr("id"));
scunliffe
+7  A: 

There are two problems:

  • .attr() is a function jQuery objects have, you have a DOM element (you would need $(anchor) to use jQuery methods against the element).
  • You don't need it anyway, the .id property will work (and be much faster), like this:

 alert(anchor.id);
Nick Craver
+1 for mentioning speed increase of `anchor.id`. I get so tired of seeing people write inefficient code just because they don't understand the overhead of frameworks.
steven_desu