Search code examples
javascriptmethodsattributestemplate-literals

using template literals with classlist attribute


javascript newbie here. I'm trying to implement template literals to change the second part of a variable name while calling the toggle method with the classlist attribute. Here's what I have:

bigBoxRight.classList.toggle("turnOff");

and this is what i'm trying to accomplish:

bigBox`${player}`.classList.toggle("turnOff");

Player can be both "Right" or "Left" and it's a string. Is this even possible?


Solution

  • What I would do is to save another variable that will get the element you need based on your decision and then get the classlist for it

    For example

    const bigBoxRight = docemnt.querySelector...
    const bigBoxLeft = docemnt.querySelector...
    
    const elemRef = true* ? bigBoxRight : bigBoxLeft 
    
    elemRef.classList.toggle("turnOff");
    
    *-  Your logic for when you need the right or the left  bigbox element
    

    Tim's solution might be cleaner if you know when you need the right element or the left