Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Classlist validation for unique selected item

So I'm trying to create a chat application like messenger. When I press the button, a new conversation should be started. I want to add a list item in my overview bar on the left but there can only be one selected, and that one has the 'history-item-selected' classname. So every new convo gets that classname, while the others ones get another classname to change it's appearance but it won't work.

const newConvoButton = document.getElementById("newmessage");
const addNewConvo = (e) => {
  e.preventDefault();
  const myMessages = document.getElementById('history');

  let newListItem = document.createElement('li');

  newListItem.textContent = "user " + Math.floor(Math.random(2 - 100) * 100);
  myMessages.appendChild(newListItem);

  if (newListItem.classList = 'history-item-selected') {
    newListItem.classList.add('history-item-selected');
  } else {
    newListItem.classList.add('history-item')
  };
};
newConvoButton.addEventListener('click', addNewConvo);
<main>
  <div id="top">
    <span>
        <h2>My conversations</h2>
      </span>
    <button type="submit" id="newmessage">+</button>
  </div>

  <div id="messagecontainer">
    <ul id="history"></ul>

    <id id="chatscreen">
      <ul id="messages">
        <li>yolo</li>
      </ul>
      <div id="messagebottom">
        <input type="text" placeholder="Start met typen" size="28" height="auto"> <button type="submit">Send</button>
      </div>
    </id>
  </div>
</main>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is a "tautological" way to do what you are trying to do.

var addNewConvo = (e)=> {
  var nodes = document.querySelectorAll(".history-item-selected");
  nodes.forEach(function(elem) {
    this.classList.remove("history-item-selected");
  });
  e.target.classList.add("history-item-selected");
}

In your CSS, you should have something like

.history-item {
  /*Styles for history-item*/
}

.history-item.history-item-selected {
  /*Styles for elements with both */
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda