Skip to content

Instantly share code, notes, and snippets.

@james-zedd
Last active August 18, 2022 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james-zedd/703c3ecfa8111ea3bcb3970f0e543bd1 to your computer and use it in GitHub Desktop.
Save james-zedd/703c3ecfa8111ea3bcb3970f0e543bd1 to your computer and use it in GitHub Desktop.
Creating elements in DOM using DocumentFragment()
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