maky maky - 1 year ago 50
Javascript Question

how to display and style a list based on array

I'm trying to display a html list based on array like this:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

I can do:

var arrayLength = fruits.length;
for (var i = 0; i < arrayLength; i++) {

but is there a way of checking for the first element and base on that can I add specyfic class to it like this?

<li class="className">Banana</li>

Answer Source

so thanks to @pranav-c-balan

var arrayLength = fruits.length,li=''; 
for (var i = 0; i < arrayLength; i++) { 
li += '<li' + (i==0 ? ' class="className"' : '') + '>' + fruits[i] + '</li>'; 

this code did the trick, thank you