Vanilla JS Thursday
Another day, some more notes from Vanilla JS Academy class of October 2021. Fewer notes than the other days this week, but more coding happened today. 🥳
Create markup from an array
These are two different approaches. Not quite sure which I prefer, but I think perhaps the first because the order of the HTML is logical. The first technique is at first glance a tad more to wrap my head around, but it handles the operation in one swoop quite elegantly once you get used to it, I reckon.
With Array.map() and Array.join()
const cityList = document.querySelector("#cities");
const array = ["Oslo", "Berlin", "Taipei", "New York", "Bergen"];
// Inject into the DOM the result of setting up <ul>
// then transform the array content with map() to wrap in <li>
// and use array method join() to create a single string
cityList.innerHTML =
"<ul>" +
array
.map(function (city) {
return "<li>" + city + "</li>";
})
.join("") +
"</ul>";
Or alternatively with a for...of loop
const cityList = document.querySelector("#cities");
const array = ["Oslo", "Berlin", "Taipei", "New York", "Bergen"];
let listItems = "";
// Loop though each item in the array and add to the string
for (const city of array) {
listItems += "<li>" + city + "</li>";
}
// Finally wrap in <ul> and inject into the DOM
cityList.innerHTML = "<ul>" + listItems + "</ul>";
I could write the second in a more verbose way that builds up a string with starting with <ul>
, then adds the list items before the final closing </ul>
in that order — but that became pretty lengthy.