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.
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.
Share edited Feb 26, 2012 at 15:19 Arman Saparbekov asked Feb 26, 2012 at 14:42 Arman SaparbekovArman Saparbekov 392 silver badges11 bronze badges 3- Are you having a particular problem? What have you tried to do, any research at all? What went wrong? – David Thomas Commented Feb 26, 2012 at 14:48
- possible duplicate of jQuery count child elements and how to add and remove css class. – Felix Kling Commented Feb 26, 2012 at 15:34
- Also you can find solutions to most of your problems in the documentation: api.jquery. – Felix Kling Commented Feb 26, 2012 at 15:40
2 Answers
Reset to default 4Using 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');
});
Relatively easy:
var numOfElementsOfClassName = $('.classNameToFind').length;
var particularIndexToApplyNewClass = 3;
$('.classNameToFind').eq(particularIndexToApplyNewClass).addClass('newClassName');
References:
addClass()
.eq()
.