0

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>
2
  • 1
    var i = $('#destaques .banner').addClass('test').length, Commented Mar 22, 2011 at 18:57
  • Working for me. Commented Mar 22, 2011 at 18:58

2 Answers 2

6

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");
Sign up to request clarification or add additional context in comments.

2 Comments

You can simplify that even further with a selector: $("#destaques .banner").addClass("test");
@FarligOpptreden, thanks for the reminder, updated the answer with your suggestion.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.