1

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?

4
  • 2
    Are you using jQuery? Like your .attr syntax implies Commented Oct 28, 2010 at 22:25
  • yes! Looks like I found my problem. Everyone hit the nail on the head. Commented Oct 28, 2010 at 22:33
  • Also, you should really use the console to debug (console.log instead of alert()). Alerts are much harder. getfirebug.com or your built-in dev tools on your browser will really help. Commented Oct 28, 2010 at 22:44
  • How about some documentation for good ole JavaScript and no jQuery developer.mozilla.org/en/DOM/element.getAttribute Commented Oct 28, 2010 at 23:38

4 Answers 4

8

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+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.
3

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").

Comments

3

if you are using jquery, then you need this:

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

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.