简体   繁体   中英

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>
  

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM