Currently, I am attempting to create a button that can toggle a specific style for various sections of my website, such as changing the background colors of certain elements.
While the buttons work correctly when there is only one element in place, I encounter an issue when multiple elements are involved. For instance, if I have thing One and thing Three, the button only affects the first one and not all elements with the same id.
I hope I explained that adequately; I am relatively new to coding and this marks my initial attempt at building a website. So please bear with me on this hahahhaha
var blue = document.getElementById('blue');
function changeBlue() {
for(var i = 0; i < blue.classList.length; i++) {
if(blue.classList[i].indexOf('body') >= 0) {
blue.classList.remove('body');
blue.classList.add('blue');
} else {
blue.classList.remove('blue');
blue.classList.add('body');
}
}
}
var pink = document.getElementById('pink');
function changePink() {
for(var i = 0; i < pink.classList.length; i++) {
if(pink.classList[i].indexOf('body') >= 0) {
pink.classList.remove('body');
pink.classList.add('pink');
} else {
pink.classList.remove('pink');
pink.classList.add('body');
}
}
}
.blue { font-family: Helvetica;
font-size: 18px;
color: #ffffff;
background-color:#003eff;
}
.pink { font-family: Helvetica;
font-size: 18px;
color: #ffffff;
background-color:#eb00ff;
}
.body { font-family: Helvetica;
font-size: 18px;
color: #000000;
background-color:#ffffff;
}
<button class="body" onclick="changeBlue()">Make Blue</button>
<button class="body" onclick="changePink()">Make Pink</button>
<span class="body" id="blue">thing One</span>
<span class="body" id="pink">thing Two</span>
<span class="body" id="blue">thing three</span>