When you code in JS, there is always some time that you need to create some html list with JS from array or list or something else. I knew the trivial way with a simple for loop, but when I put myself a little deeper into JS, then I found a way to make it with a chained function. What is a chained function? Something that reminds me a lot to Python, but it is still JS. Thus, something like this – array.forEach(function(param){…}.
Thus, if you have an array of elements as I have in the sample code, this is the expected result:
And this is how you obtain it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE HTML> <html> <head> </head> <body> <div id="myList"></div> <script type="text/javascript"> var names = ['vitosh','academy','dot','com']; var ul = document.createElement('ul'); document.getElementById('myList').appendChild(ul); names.forEach(function(name){ var li = document.createElement('li'); ul.appendChild(li); li.innerHTML += name; }); </script> </body> </html> |
If for any reason you need to locate my code in GitHub, you may click the link.
That is all! 🙂