2
votes

I'm trying to add a class or a css style using the following js but getting a console error

var i = 0;

$(".question")[i].addClass("show");

get the following console log error: Uncaught TypeError: Object # has no method 'addClass'

or / and

$(".question")[i].css("display", "block");

get the following console log error: Uncaught TypeError: Object # has no method 'css'

used info from http://api.jquery.com/get/

EDIT
Still doesn't working if get rid of the variable i, and use numbers 0 or 1

1
Can you show your markup? - Karl Anderson
$(".question").eq(i).addClass("show"); - lashab

1 Answers

7
votes

When you access an item from a collection with a subscript like [i], you're actually unwrapping it from the jQuery object, and accessing a raw DOM node, which doesn't have methods like addClass and css.

Use .eq() instead:

var i = 0;
$(".question").eq(i).addClass("show");
$(".question").eq(i).css("display", "block");