Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!