Federico
Federico

Reputation: 1422

addClass to last item of array

I have this function that gives me all the numbers from 1 to 870. How can I get the 870 (the last item) and add a Class to it?

Thanks in advance.

var points = new Array(870);
for (var i = 0; i < 870; i++){points[i] = i + 1;}
$(".numbers").html(points.join(', '))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=numbers></div>

Upvotes: 1

Views: 861

Answers (2)

Get Off My Lawn
Get Off My Lawn

Reputation: 36331

What you could do is use the :last-child selector on the numbers class, and add it that way like so:

var points = new Array(870);
for (var i = 0; i < 870; i++) {
  points[i] = `<span>${i + 1}</span>`
}
$(".numbers").html(points.join(' '))
  .find(':last-child')
  .addClass('myClass')
.myClass {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="numbers"></div>

Upvotes: 2

Add a span element and a custom class to it to the last point.

For dynamic array use point.length-1 instead 869

var points = new Array(870);
for (var i = 0; i < 870; i++){points[i] = i + 1;}
points[points.length-1] = '<span class="custom-class">'+points[points.length-1]+'</span>'
$(".numbers").html(points.join(', '))
.custom-class{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=numbers></div>

Upvotes: 3

Related Questions