Kuttan Sujith
Kuttan Sujith

Reputation: 7979

dynamically changing class

I have a lot of items of same class “first”

I have tried:

var mailHeadding = $('.first');
$.each(mailHeadding, function (indx) {
    if (indx == mailHeadding.length) {
        mailHeadding[indx].removeClass('first').addClass('last');
    }
    else if (indx != 0) {
        mailHeadding[indx].removeClass('first');
    }
});

Also mailHeadding[indx] replaced by "this"

Still this won't work.

Upvotes: 1

Views: 118

Answers (4)

user113716
user113716

Reputation: 322502

$('.first:gt(0)').removeClass('first').last().addClass('last');

This uses the greater than selector to get all elements with the .first class greater than the zero-based index provided (in this case 0, meaning the first).

Then it uses .removeClass() to remove the first class from them, and uses .last() to jump to the last one and uses .addClass() to add the last class.

Upvotes: 4

lonesomeday
lonesomeday

Reputation: 237905

Try this:

$('.first').slice(1)
    .removeClass('first')
    .last().addClass('last');

To explain what's going on here:

  1. Select all members of the first class
  2. Use the slice() method to choose all but the first element in the selection
  3. Use the removeClass() method to remove the first class from these elements.
  4. Use the last() method to select only the final element in the selection
  5. Use the addClass() method to add the last class to this element.

Upvotes: 1

poke
poke

Reputation: 387815

if (indx == mailHeadding.length)

This is your problem. The index is between 0 and length - 1 (inclusive). So if the length is 5, the indizes are 0, 1, 2, 3, 4. So your comparison never results in true. You have to compare with length - 1 instead.

Upvotes: 1

DoXicK
DoXicK

Reputation: 4812

$('.<classes>:first-child').addClass('first');
$('.<classes>:not(:first-child)').removeClass('first');
$('.<classes>:last-child').addClass('last');

that sums up how you can use jquery to solve this problem

Upvotes: 0

Related Questions