I’ve got an array of comments, and want a part of them to be hidden, if hidden param is true, before a user clicks on a "load more" button.
But it doesn’t work properly, instead it adds hidden class to all comments but the last one.
async function comments(...arr) {
let i = 0;
const container = document.querySelector('.comments')
function setHidden(h) {
if (h === true) {
$('.comment').addClass('hidden')
} else {
$('.comment').removeClass('hidden')
}
}
for (let i of arr) {
await setHidden(i.hidden)
$(container).append(`<div class="comment">${i.comment}</div>`)
}
}
comments({
comment: 'hi'
}, {
hidden: true,
comment: 'how are you'
}, {
hidden: true,
comment: 'where are you from?'
});
>Solution :
Following on from Rory’s answer, if you did want to use jQuery throughout (you’re mixing and matching with vanilla JS at the moment) you can.
function comments(...arr) {
const container = $('.comments');
$.each(arr, (i, obj) => {
const comment = $(`<div class="comment">div>`);
if (obj.hidden) comment.addClass('hidden');
comment.text(obj.comment);
$(container).append(comment);
});
}
comments({
comment: 'hi'
}, {
hidden: true,
comment: 'how are you'
}, {
hidden: true,
comment: 'where are you from?'
});
.hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="comments"></div>