maky maky - 4 months ago 9
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++) {
console.log(fruits[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>
<li>Orange</li>
<li>Apple</li>
<li>Mango</li>

Answer

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

Comments