Class Manipulation Example

HTML
<div class="box"> </div> <button onClick="changeRed()"> red </button> <button onClick="changeBlue()"> blue </button> <button onClick="changeYellow()"> yellow </button>
CSS
.box{ margin: 50px; width : 200px; height: 200px; } .red{ background: red; } .blue{ background: blue; } .yellow{ background: yellow; }
JAVASCRIPT
function changeRed(){ box = document.querySelector('.box'); box.classList.remove('red'); box.classList.remove('blue'); box.classList.remove('yellow'); box.classList.add('red'); } function changeBlue(){ box = document.querySelector('.box'); box.classList.remove('red'); box.classList.remove('blue'); box.classList.remove('yellow'); box.classList.add('blue'); } function changeYellow(){ box = document.querySelector('.box'); box.classList.remove('red'); box.classList.remove('blue'); box.classList.remove('yellow'); box.classList.add('yellow'); }
Expand for more options Login