Dave
Dave

Reputation: 9147

Help me understand whats wrong with my javascript

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?

Upvotes: 1

Views: 208

Answers (4)

Chuck
Chuck

Reputation: 237010

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.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630379

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);

Upvotes: 8

scunliffe
scunliffe

Reputation: 63580

if you are using jquery, then you need this:

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

Upvotes: 3

Vivin Paliath
Vivin Paliath

Reputation: 95508

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

Upvotes: 3

Related Questions