CodeBank
CodeBank

Reputation: 72

Syntax for using attr() on individual item from selector array of matches

I'm trying to call attr() on an item from an array of selector matches, but it's telling me that method doesn't exist. I suppose I need to cast the array item, but I'm not finding how to do this.

$("input:radio[id$=Product]")[0].attr('checked', true);

The error is "Object doesn't support property or method 'attr'".

Upvotes: 0

Views: 33

Answers (2)

Raymond Reddington
Raymond Reddington

Reputation: 1837

The problem causes [0], in jquery you have :first option, i.e. $("input:radio[id$=Product]:first"), so maybe this will do the trick.

$("input:radio[id$=Product]:first").attr('checked', true);

Upvotes: 0

dsh
dsh

Reputation: 12214

Pay close attention to the type of the object this expression evaluates to: $("input:radio[id$=Product]")[0]. It is not a jQuery object, so it does not have any jQuery methods.

One solution: wrap it in a jQuery object:

$( $("input:radio[id$=Product]")[0] ).attr('checked', true)

Another solution (better, I think): use first() to reduce the set of elements to the first one only:

$("input:radio[id$=Product]").first().attr('checked', true)

Upvotes: 4

Related Questions