Using classList in Javascript function to add CSS classes, but styles conflict because latest class does not take precedence
Mary-Kate Olsen
Mary-Kate Olsen 2023-09-10 17:10:38
0
2
478

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

const showMoreIcon = document.querySelector('.cta-icon'); function myFunction(){ const btnIcon = cardsOnShow >= cards.length ? 'arrow-up' : 'arrow-down'; showMoreIcon.classList.add(btnIcon); }

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

How to ensure that whenarrow-upis added,arrow-downis removed and vice versa? I've previously usedtoggleto implement a simple open/close icon, but this doesn't work as it may expand multiple times before closing.

Mary-Kate Olsen
Mary-Kate Olsen

reply all (2)
P粉579008412

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') } }
    P粉395056196

    Cascading takes into account many factors a>, which is a set of rules used to determine which rule "wins" when two conflicting rules are applied to the same element.

    The order in which classes are defined on HTML elementsis not one of these factors.

    and
    are the same as far as cascading is concerned.

    Deleteclasses that should not be applied.

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

    Or write the CSS in a way that only cares about a single class to change the orientation:

    .arrow { /* arrow up CSS */ } .arrow.invert { /* override the up rule and replace with the down rule }

    Then

    if (cardsOnShow >= cards.length) { showMoreIcon.classList.remove("invert"); } else { showMoreIcon.classList.add("invert"); }

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!