Last active
August 18, 2022 14:02
-
-
Save james-zedd/703c3ecfa8111ea3bcb3970f0e543bd1 to your computer and use it in GitHub Desktop.
Creating elements in DOM using DocumentFragment()
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
const USER_DATA_URL = 'https://jsonplaceholder.typicode.com/users'; | |
const main = document.getElementById('main'); | |
async function init() { | |
const fetchUsers = await fetch(USER_DATA_URL); | |
const users = await fetchUsers.json(); | |
users.forEach(user => { | |
const fragment = userFragment(user); | |
main.appendChild(fragment); | |
}); | |
} | |
function userFragment(user) { | |
const fragment = new DocumentFragment(); | |
const container = createElement('div'); | |
const nameElement = createElement('p', user.name); | |
const phoneElement = createElement('p', user.phone); | |
container.classList.add('container'); | |
container.appendChild(nameElement); | |
container.appendChild(phoneElement); | |
fragment.append(container); | |
return fragment; | |
} | |
function createElement(elem, text) { | |
const element = document.createElement(elem); | |
if (text) { | |
const textNode = document.createTextNode(text); | |
element.appendChild(textNode); | |
} | |
return element; | |
} | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment