Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Instead of trying to dynamically create variable names, you should get the element you are trying to toggle the class on first.

Assuming bigBoxRight or bigBoxLeft is the id of the element, you can use your template literals to get the element first:

var elem = document.querySelector(`#bigBox${player}`)

Then you can do:

elem.classList.toggle("turnOff");
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!