I want to add an active class to the second span and remove it from the first span when clicking on the ” Click me” with javascript
<span class="click">Click me<span/>. <div class="subtab"> <span class="first active" data-tabname="reviews" tabindex="0">Reviews</span> <span class="first " data-tabname="questions" tabindex="0">Questions </span> </div>
Advertisement
Answer
This will work
HTML:
<div> <span class="span-class active">span 1</span> <span class="span-class">span 2</span> </div> <button id="btn"> alter </button>
Script:
let spanElements = document.getElementsByClassName("span-class"); let btn = document.getElementById("btn"); btn.addEventListener('click', () => { if(spanElements[0].classList.contains('active')) { spanElements[1].classList.add("active"); spanElements[0].classList.remove("active"); } else { spanElements[0].classList.add("active"); spanElements[1].classList.remove("active"); } });
CSS
.active { color: red; }