Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add class to chosen elements in array?

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?'
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading