WeakSet
by Artem
CSS
.post {
font-family: sans-serif;
color: #333;
border: 2px dashed #ccc;
padding: 10px 15px;
margin-bottom: 10px;
}
.read {
background-color: tomato;
}
JavaScript
'use strict';
const posts = [{
id: 1,
author: 'Artem',
post: 'Hello'
}, {
id: 2,
author: 'Illuxa',
post: 'Hi'
}];
let readPosts = new WeakSet();
function renderPosts() {
const postList = document.createElement('div');
posts.forEach(post => {
const element = document.createElement('div');
element.innerHTML = `<small>${post.author}</small><p>${post.post}</p>`;
element.classList.add('post');
element.dataset.id = post.id;
postList.append(element);
});
document.body.append(postList);
postList.addEventListener('click', event => {
const postID = event.target.closest('.post').dataset.id;
const post = posts.find(post => post.id = postID);
readPosts.add(post);
for (let post of posts) {
if (readPosts.has(post)) {
const element = document.querySelectorAll(`[data-id="${post.id}"]`)[0];
_addNewPostClass(element);
}
}
});
}
function _addNewPostClass(element) {
element.classList.add('read');
}
renderPosts();