Lucas Veiga
Lucas Veiga

Reputation: 1795

jQuery Each() function not working

I'm trying to add a class to each div.banner inside of my #destaques, but isn't working. What's happening?

JS:

$(document).ready(function() {
  bannerRotator("#destaques");
});



function bannerRotator(element) {

  // Conta quantos banners existem:

  i = 0;

  $(element).find(".banner").each(function() {
    i++;
    $(this).addClass("test");
  });

  alert(i);

  //

}

HTML:

<div id="destaques">
<div class="banner"><img src="images/001.jpg"/></div>
<div class="banner"><img src="images/002.jpg"/></div>
<div class="banner"><img src="images/003.jpg"/></div>
</div>

Upvotes: 1

Views: 4060

Answers (2)

Michael Koper
Michael Koper

Reputation: 9781

Try this

jQuery.each($("div.banner"), function() {
  i++;
  $(this).addClass("test");
});

But if you just want to add the class you can also do it in the following one liner

alert($('div.banner').addClass("test").length);

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

addClass will work on a collection automatically.

$("#destaques").find(".banner").addClass("test");

Example on jsfiddle.

side note: this could be also be simplified to

$("#destaques .banner").addClass("test");

Upvotes: 6

Related Questions