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 >Click me<span/>.
<div >
<span data-tabname="reviews" tabindex="0">Reviews</span>
<span data-tabname="questions" tabindex="0">Questions </span>
</div>
CodePudding user response:
This will work
HTML:
<div>
<span >span 1</span>
<span >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;
}