Skip to content

Instantly share code, notes, and snippets.

@boehs
Created July 28, 2021 04:28
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 boehs/1fc01ac834cf1d8ea712a9e7ad369eea to your computer and use it in GitHub Desktop.
Save boehs/1fc01ac834cf1d8ea712a9e7ad369eea to your computer and use it in GitHub Desktop.
JSON blog
let d = [{
"title": "post one",
"date": 1627421886,
"content": "lorum ipsut"
},
{
"title": "post two",
"date": 1727421886,
"content": "lorum ipsut dolar",
"tags": ["a", "b", "c"]
}
]
const author = "Evan"
function dnow(timestamp) {
return new Date(timestamp * 1000).toLocaleString();
}
render(d)
function render(posts) {
const grid = document.querySelector('.list');
if (posts.length > 0) {
posts.forEach(post => {
const postDiv = createElement('div', grid);
const titleH1 = createElement('h1', postDiv);
titleH1.textContent = post.title;
const infoH3 = createElement('h3', postDiv);
infoH3.textContent = `On ${dnow(post.date)} by ${author}`;
const contentDiv = createElement(
'div',
postDiv,
'content-div',
);
const contentPara = createElement('p', contentDiv);
contentPara.textContent = post.content;
if (
post.tags !== undefined &&
post.tags.length > 0
) {
const tagsDiv = createElement(
'div',
postDiv,
'post-tags',
);
const tagUL = createElement('ul', tagsDiv);
post.tags.forEach(item => {
const itemLI = createElement('li', tagUL);
itemLI.textContent = item;
});
}
});
}
}
function createElement(type, parent, classList) {
const element = document.createElement(type);
if (classList !== undefined) {
typeof classList === 'Array' && classList.length > 0 ?
element.classList.add(...classList) :
(element.className = classList);
}
parent.append(element);
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment