最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery count the elements by class and set the another class a certain element in the list - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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');
});​

Relatively easy:

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

References:

  • addClass().
  • eq().

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论