divHelper11
divHelper11

Reputation: 2208

Add different classes to elements with jquery

I need to give different Classes to each <a>. I can do it only with js/jquery.

<ul class="ulClass">
<li><a></a></li>
<li><a></a></li>
<li><a></a></li>
<li><a></a></li>
</ul>

My attempt of giving them Classes (className1, className2, className3):

jQuery(document).ready(function(){
    var classNumber = 1;
    var className = "className" + classNumber;
    jQuery(".ulClass:nth-child(1)").addClass(className + classNumber++);
    jQuery(".ulClass:nth-child(2)").addClass(className + classNumber++);
    jQuery(".ulClass:nth-child(3)").addClass(className + classNumber++);
    jQuery(".ulClass:nth-child(4)").addClass(className + classNumber++);
});

My code just gives class name to the ul element... In addition it is className11. What happens wrong here?

Upvotes: 0

Views: 61

Answers (3)

Manish Tuteja
Manish Tuteja

Reputation: 205

Checkout Jsfiddle here.

In order to have a unique class name for the <a> elements in your unordered list. You can iterate over each "a" using $(".ulClass a").each and then use addClass(className) on the current context this. And since you want the anchor tags to have a unique class name, so I am using a classNum variable which increments by 1 after every iteration.

var classNum = 1;
$(".ulClass a").each(function(){
    var className = "className" + classNum;
    $(this).addClass(className);
    classNum++;
});

Upvotes: 1

smdsgn
smdsgn

Reputation: 1746

You can iterate over your links with the .each() jQuery method.
See the documentation
This way you can use the index of the current iteration of the loop for your class name.

$(".ulClass a").each(function(index){
  $(this).addClass("className" + index);
});

Upvotes: 2

The Process
The Process

Reputation: 5953

You can do it like this:

  var classNumber = 1;
  $(".ulClass a").each(function(){
    var className = "className" + classNumber;
    $(this).addClass(className);
    classNumber++;

});

Upvotes: 1

Related Questions