Reputation: 7979
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
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
Reputation: 237905
Try this:
$('.first').slice(1)
.removeClass('first')
.last().addClass('last');
To explain what's going on here:
first
classslice()
method to choose all but the first element in the selectionremoveClass()
method to remove the first
class from these elements.last()
method to select only the final element in the selectionaddClass()
method to add the last
class to this element.Upvotes: 1
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
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