Skip to content
Advertisement

I want to add an active class to second span on a div with two spans with the same class with javascript

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;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement