EasierSaidThanDone
EasierSaidThanDone

Reputation: 1897

jQuery doesn't find elements or its attributes

I've got this:

<h1 id="test" class="test">

and in a script part this:

alert($('#test').id)
alert($('.test').id)

jQuery is definitely loaded. But I get undefined in the alert box - both times. If I use the regular getElementById, it works and shows test.

What the heck is wrong (with me)

here's an example http://jsfiddle.net/tF6bd/

Upvotes: 2

Views: 2667

Answers (2)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

You can use attr or prop, the difference is that attr return undefined if the attribute haven't been set.

Examples:
alert($('test').attr('id'));
alert($('test').prop('id'));

Demos:

References:

Upvotes: 0

Ram
Ram

Reputation: 144689

change:

alert($('#test').id)

to:

alert($('#test').attr('id'))

or:

alert($('#test')[0].id)

for jQuery objects you should use attr() method.

Upvotes: 4

Related Questions