18
var slides = $(".promo-slide");
slides.each(function(key, value){
    if (key == 1) {
        this.addClass("first");
    }
});

Why do I get an error saying:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'addClass'

From the above code?

o01
  • 5,191
  • 10
  • 44
  • 85

2 Answers2

34

Inside jQuery callback functions, this (and also value, in your example) refers to a DOM object, not a jQuery object.

var slides = $(".promo-slide");
slides.each(function(key, value){
    if (key == 0) { // NOTE: the key will start to count from 0, not 1!
        $(this).addClass("first"); // Or $(value).addClass("first");
//------^^----^       
    }
});

BUT: In your case, this is easier:

$(".promo-slide:first").addClass("first");

And when all .promo-slide elements in the same container, a solution in pure CSS is even easier:

.promo-slide:first-child {
    /* ... */
}

As an aside, I find it a useful convention to prefix variables that contain a jQuery object with a $:

var $slides = $(".promo-slide");
$slides.each( /* ... */ );
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • 3
    1 Minute, 5 upvotes === jQuery effect. Also the each loop is 0 based so he's adding the class "first" to the second element. – Raynos Jun 20 '11 at 09:17
  • @Orolin: ...because `this` within the `each` function is a reference to the raw DOM element, so if you want to use jQuery functions, you have to make a jQuery instance for that element: [Details in the documentation.](http://api.jquery.com/each/) – T.J. Crowder Jun 20 '11 at 09:18
  • 1
    @Tomalak, I think `.each` gives indexes starting from 0, so you should do `$('.promo-slide:eq(1)')` instead, in your second code fragment. – sharat87 Jun 20 '11 at 09:19
  • @Raynos, @Shrikant: Yes, you are absolutely correct. Will fix this. – Tomalak Jun 20 '11 at 09:19
  • 3
    @Raynos: Regarding the "jQuery effect" - I find that a little embarrassing myself. There are far better and more "costly" answers (in terms of time needed to write) on this site that hardly catch a vote, while the really obvious ones go through the roof in no time. – Tomalak Jun 20 '11 at 09:23
3

You probably want to do:

$(this).addClass
ninjagecko
  • 88,546
  • 24
  • 137
  • 145