Dora Dora - 1 month ago 14
HTML Question

what's the best practice to add tags into the array using append? jQuery

let's say I have an array like this which is being append into the ul like below

data['productDetailOptions'] = ['red', 'blue', 'big', 'small', 'medium'];

$('.cart-productDetailOptions ul').append(data['productDetailOptions']);

what's going on above does not have the
tag I know that for sure I can use a for loop to loop through each array and add the tag then assign them into a new variable.

I am wondering if there's an easier and shorter way so I don't have to use a loop?

EDIT: My bad, I should say any other ways than using a for loop. Sorry for misunderstandings


There is .map method for every array, so the most efficient way for me looks like this :

$('.cart-productDetailOptions ul').append(data['productDetailOptions'].map( item => "<li>"+item+"</li>" ) );

Note: I'm using ES6 arrow functions. Which has it's equivalent :

$('.cart-productDetailOptions ul')
    .append( data['productDetailOptions'].map( function(item) { 
        return "<li>"+item+"</li>" 
    } ) );

Note 2 : Thanks for the comment by @Dora. Actually $(..).append accepts both Array and string, so the .join is unnecessary.