Home > Blockchain >  How to switch classes with JS by ID
How to switch classes with JS by ID

Time:10-29

I would like to be able to select only one answer, by Id!

So I started created this js function :

function switchclass() {

    let elements = document.getElementsById('A');

    for (var i = 0; i < elements.length; i  ) 

    {                         
        elements[i].className = 'selected';

        let unselectedelements = document.getElementById('B','C','D')
        
        {
            unselectedelements.className = 'notselected';
        }
     
        {
    }

}

Visual

It still don't work and I don't know what to do then :/ Thanks for any fix!

CodePudding user response:

document.getElementByID returns one element matching the id attribute. In this use case, you should be using class that is common across all the list items. On click of the element, remove the selected class from all the elements and apply it on the clicked element.

let list = document.querySelectorAll('.list');

list.forEach(elem => {
  elem.onclick = function() {
    list.forEach(el => {
      el.classList.remove('selected');
    });
    elem.classList.add('selected');
  }
})
.list {
  width: 100%;
  padding: 5px;
  margin: 10px;
  border: 1px solid gray;
  text-align: center;
  cursor: pointer;
}

.selected {
  background: pink;
}
<div class="list">A</div>
<div class="list">B</div>
<div class="list">C</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

First of all document.getElementById(id) can only take one id as a parameter. After that you have to make conditions as per your preference.

  • Related