Last active
January 23, 2020 12:44
-
-
Save nikasulo/f2c4102778e9d043eb77f008edc37a92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<ul id="root"> | |
</ul> | |
<script src="./map.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Say you had a list of elements to render in your html <ul> element with an id of root | |
// Let's select that element, using the query selector method | |
const addElementsToUl = () => { | |
const root = document.querySelector('#root'); | |
// Now the list of elements to render. We'll use a simple array of numbers | |
const elementsToRender = [0,1,2,3,4,5]; | |
// Now we use map to store a copy of the array in another variable made of <li> elements | |
// Map doesn't mutate the array, it returns a shallow copy of it | |
// First method | |
// First store the list items in a variable | |
const listItems = elementsToRender.map(element => `<li>${element}</li>`); | |
// set the inner html of the ul to the list items. Don't forget to join them to remove commas between them since it's | |
// an array | |
root.innerHTML = listItems.join(''); | |
//Second Method | |
// Do it all in one swoop. store the list items, join them and set the inner html | |
root.innerHTML = elementsToRender.map(element => `<li>${element}</li>`).join(''); | |
}; | |
document.addEventListener('DOMContentLoaded', addElementsToUl()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment