search

Home  >  Q&A  >  body text

Using classList in Javascript function to add CSS classes, but styles conflict because latest class does not take precedence

My function counts the number of cards visible on the screen and if all are shown, I add the arrow-up class to my icon, if some cards are still hidden from the user, arrow adds -down icon.

const showMoreIcon = document.querySelector('.cta-icon');

function myFunction(){
   const btnIcon = cardsOnShow >= cards.length ? 'arrow-up' : 'arrow-down';
   showMoreIcon.classList.add(btnIcon);
}
<span class="medium-icon"></span>

This works, but I can see in the DOM that the correct class is added to the span as I would expect it to be since the arrow-down class was added first (in The user has to expand the content multiple times before all visible cards are shown) - then, although the arrow-up class is added, it does not override the arrow-down. p>

How to ensure that when arrow-up is added, arrow-down is removed and vice versa? I've previously used toggle to implement a simple open/close icon, but this doesn't work as it may expand multiple times before closing.

P粉738821035P粉738821035484 days ago593

reply all(2)I'll reply

  • P粉579008412

    P粉5790084122023-09-11 14:59:10

    I recommend deleting courses you no longer need:

    function myFunction(){
       if (cardsOnShow >= cards.length) {
          showMoreIcon.classList.add('arrow-up')
          showMoreIcon.classList.remove('arrow-down')
       } else {
          showMoreIcon.classList.remove('arrow-up')
          showMoreIcon.classList.add('arrow-down')
       }
    }
    
    

    reply
    0
  • P粉395056196
  • Cancelreply