javascript - Create li from loop through array and display to HTML as a list -


i learning javascript , want loop array , display html list. how can that?

array: var array = ['slide 1', 'slide 2', 'slide 3', 'slide 4', 'slide 5', 'slide 6', 'slide 7', 'slide 8', 'slide 9'];

javascript:

function listitem(item){    (var = 0; < item.array.length; i++){      var list = item.array[i];            list = document.createelement('li');      document.getelementbyclass('box').appendchild(list);            console.log(list);    }     }
<div class ="box"><ul></ul></div>

you use es6 method reduce , template literals. use them this:

var array = ['slide 1', 'slide 2', 'slide 3', 'slide 4', 'slide 5', 'slide 6', 'slide 7', 'slide 8', 'slide 9'],    // reduce iterate on array items , returns single value.    listitems = array.reduce((result, item) => {      // add string result current item. syntax using template literals.      result += `<li>${item}</li>`;            // return result in reduce callback, value or result in next iteration.      return result;    }, ''); // '' empty string, initial value result.    // element dom in display list, should ul or ol element.    resultelement = document.getelementbyid('result');    // set inner html  resultelement.innerhtml = listitems;
<ul id="result"></ul>

for more information on reduce see here: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/reduce. , if want know more template literals check here: https://developer.mozilla.org/en-us/docs/web/javascript/reference/template_literals


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -