[jquery] 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?

The answer is


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);
});

It's possible without jQuery too! :)

_x000D_
_x000D_
let countries = ['United States', 'Canada', 'Argentina', 'Armenia', 'Aruba'];_x000D_
_x000D_
// The <ul> that we will add <li> elements to:_x000D_
let myList = document.querySelector('ul.mylist');_x000D_
_x000D_
// Loop over the Array of country names:_x000D_
countries.forEach(function(value, index, array) {_x000D_
  // Create an <li> element:_x000D_
  let li = document.createElement('li');_x000D_
_x000D_
  // Give it the desired classes & attributes:_x000D_
  li.classList.add('ui-menu-item');_x000D_
  li.setAttribute('role', 'menuitem');_x000D_
_x000D_
  // Now create an <a> element:_x000D_
  let a = document.createElement('a');_x000D_
_x000D_
  // Give it the desired classes & attributes:_x000D_
  a.classList.add('ui-all');_x000D_
  a.tabIndex = -1;_x000D_
  a.innerText = value; //  <--- the country name from our Array_x000D_
  a.href = "#"_x000D_
_x000D_
  // Now add the <a> to the <li>, and add the <li> to the <ul>_x000D_
  li.appendChild(a);_x000D_
  myList.appendChild(li);_x000D_
});
_x000D_
<ul class="mylist"></ul>
_x000D_
_x000D_
_x000D_


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);
});

Other variation of Abhishek Bhalani: You can use Array.map() instead of $.each()

var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
      var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
      $('<a class="ui-all">'+ i + ': ' + item.name + '<a/>')
        .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))
  )
);

    <script type="text/javascript" >
        function aa()
        {
            var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
            var ObjUl = $('<ul></ul>');
            for (i = 0; i < YourArray.length; i++)
            {
                var Objli = $('<li></li>');
                var Obja = $('<a></a>');

                ObjUl.addClass("ui-menu-item");
                ObjUl.attr("role", "menuitem");

                Obja.addClass("ui-all");
                Obja.attr("tabindex", "-1");

                Obja.text(YourArray[i]);
                Objli.append(Obja);

                ObjUl.append(Objli);
            }
            $('.DivSai').append(ObjUl);
        }
    </script>
</head>
<body onload="aa()">
    <form id="form1" runat="server">
    <div class="DivSai" >

    </div>
    </form>
</body>

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>';

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to javascript-framework

What is the difference between React Native and React? Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate Angular JS break ForEach AngularJS passing data to $http.get request AngularJs ReferenceError: $http is not defined Difference between the 'controller', 'link' and 'compile' functions when defining a directive Pass variables to AngularJS controller, best practice? How to generate UL Li list from string array using jquery? jQuery: Check if div with certain class name exists Get epoch for a specific date using Javascript