2

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/

2
  • jQuery's factory function doesn't return DOM nodes, it returns a jQuery wrapper that contains a list of DOM nodes. Commented Jul 16, 2012 at 18:23
  • 1
    jQuery does find the elements in this case. Commented Jul 16, 2012 at 18:25

2 Answers 2

4

change:

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

to:

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

or:

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

for jQuery objects you should use attr() method.

Sign up to request clarification or add additional context in comments.

2 Comments

But: Is that readonly? If I assign a value like $(".test").attr("class") = "try" it stops execution. See jsfiddle.net/tF6bd/1
@EasierSaidThanDone for changing an attribute's value you should code $(".test").attr("class", "try")
0

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:

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.