I have been searching for an answer to my question without success. I have a unique challenge where I need to change the styles of an h1 element by adding a class based on which radio button is clicked. The issue I'm facing is that when I select a different button, the new class is added but the previous classes remain. I resorted to a brute force solution, but I know there must be a better way to achieve this with more dynamic styling options.
To see the attempt and code in action, visit: https://jsfiddle.net/ebzjknqo/4/
HTML CODE
const button = document.forms.namedItem('color');
const changeColor = (color) => {
const title = document.querySelector('#title');
title.classList.add(`title-${color}`);
console.log('classlist: ', title.classList);
title.innerHTML = `i am ${color}`;
};
button.addEventListener('change', (e) => changeColor(e.target.value));
#title {
margin: 0.5em auto;
text-align: center;
text-transform: capitalize;
}
/* RADIO BUTTONS */
#button-group {
text-align: center;
}
#button-group label {
font-size: 0.8rem;
border: rgb(117, 114, 114) solid 1px;
background-color: rgb(236, 236, 236);
border-radius: 4px;
text-transform: uppercase;
padding: 0.7em 1.5em;
}
#button-group input[type='radio'] {
opacity: 0;
z-index: 100;
width: 0;
display: none;
}
#button-group label:hover {
background-color: rgb(199, 199, 199);
cursor: pointer;
}
.btn {
padding: 0.5em 1.5em;
margin: 1em auto;
}
.title-blue {
color: blue;
}
.title-red {
color: red;
}
.title-orange {
color: orange;
}
<section class="main">
<h1 id="title">Hello World</h1>
<div id="button-group">
<form name="color">
<input
type="radio"
id="btn-red"
name="btn"
value="red"
onchange="changeColor(this.value)"
/>
<label for="btn-red">Red</label>
<input
type="radio"
id="blue"
name="btn"
value="blue"
onchange="changeColor(this.value)"
/>
<label for="blue">Blue</label>
<input
type="radio"
id="orange"
name="btn"
value="orange"
onchange="changeColor(this.value)"
/>
<label for="orange">Orange</label>
</form>
</div>
</section>