How to generate UL Li list from string array using jquery?
I have string array like
'United States', 'Canada', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bangladesh', 'Belarus', 'Belgium'**, ... etc.
I want create a dynamic list from string array like below:-
<ul class="mylist" style="z-index: 1; top: 474px; left: 228px; display: none; width: 324px;" >
<li class="ui-menu-item" role="menuitem">
<a class="ui-all" tabindex="-1">
United States
</a>
</li>
<li class="ui-menu-item" role="menuitem">
<a class="ui-all" tabindex="-1">
Canada
</a>
</li>
<li> .... </li>
.....
</ul>
How is it possible using jQuery?
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i)
{
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var aaa = $('<a/>')
.addClass('ui-all')
.text(countries[i])
.appendTo(li);
});
With ES6 you can write this:
const countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
const $ul = $('<ul>', { class: "mylist" }).append(
countries.map(country =>
$("<li>").append($("<a>").text(country))
)
);
Even better approach using array's join method
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var list = '<ul class="myList"><li class="ui-menu-item" role="menuitem"><a class="ui-all" tabindex="-1">' + countries.join('</a></li><li>') + '</li></ul>';
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i) {
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var a = $('<a/>')
.addClass('ui-all')
.text( this )
.appendTo(li);
});