1

How with jQuery/Javascript count the elements by class and set another class a certain element in the list.

It is possible?

An example, i have four elements with the class "qa" and change or add class "qa2" second element in list.

  • Are you having a particular problem? What have you *tried* to do, any research at all? What went wrong? – David Thomas Feb 26 '12 at 14:48
  • possible duplicate of [jQuery count child elements](http://stackoverflow.com/questions/4291151/jquery-count-child-elements) and [how to add and remove css class](http://stackoverflow.com/questions/2170878/how-to-add-and-remove-css-class). – Felix Kling Feb 26 '12 at 15:34
  • Also you can find solutions to most of your problems in the documentation: http://api.jquery.com/ – Felix Kling Feb 26 '12 at 15:40

2 Answers2

4

Using jquery

var el = $('.cls');
alert(el.length); // Will alert length

To add a class to the 2nd element

$(el[1]).addClass('classOne'); // first item is 0 and second item is 1 and so on

Inside a loop to add class to 2nd element using condition.

el.each(function(i){
    if(i==1) // If 2nd item then add the class
        $(el[i]).addClass('newClass');  
});​

Or this will add 'newClass' class to all elements that has class 'cls'

$('.cls').addClass('newClass')​; 

OR this will add different classes to odd and even items in the list/matched items

​$('.cls').each(function(i){
    if(!(i%2))  
        $(this).addClass('odd');
    else
        $(this).addClass('even');
});​
The Alpha
  • 143,660
  • 29
  • 287
  • 307
1

Relatively easy:

var numOfElementsOfClassName = $('.classNameToFind').length;
var particularIndexToApplyNewClass = 3;
$('.classNameToFind').eq(particularIndexToApplyNewClass).addClass('newClassName');

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • And maybe need remove the old class with `removeClass()`. – Paulo Rodrigues Feb 26 '12 at 14:56
  • I considered that, but I couldn't work out, from the original question (such as it was) whether the new class should be added, or the old class replaced. – David Thomas Feb 26 '12 at 14:57
  • You haven't given any details. What elements are you trying to find. What element do you want to add a class-name to? What's your mark-up? Do you want to *change* the class-name, or append another class-name? – David Thomas Feb 26 '12 at 15:16
  • Thanks for reply David. All I needed to it is: var el = $('.qa'); $(el[1]).addClass('qa2'); – Arman Saparbekov Feb 26 '12 at 15:33