document.querySelectorAll('.answer').forEach(ans => {
ans.onclick = (e) => {
answer = e.target.innerHTML
ans.style.background = '#222'
ans.style.color = '#fff'
e.target.style.background = '#fff'
e.target.style.color = '#222'
}
})
var classname = document.getElementsByClassName('answer');
function myFunction(e){
document.querySelectorAll('.answer').forEach(ans => {
ans.style.background = '#222'
ans.style.color = '#aeaeae'
});
e.target.style.background = '#fff'
e.target.style.color = '#000'
}
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', myFunction, false);
}
active
для единственного выбранного элемента:div.answer { background: #222; color: #aeaeae; }
div.answer.active { background: #fff; color: #000; }
const els = [...document.querySelectorAll('.answer')];
const toggle = event => {
els.forEach(el => el.classList[event.target === el ? 'add' : 'remove']('active'));
}
els.forEach(el => el.addEventListener('click', toggle));