0

newb here. I'm trying to pass a variable in my function but when I include it in my code (as a template literal) it doesnt work. I'm really tyring to keep the code clean by passing the customer number vs copying the code 4x times. Any help would be greatly appreciated.

let customer1Svg = document.querySelector("#customer1Select");
let customer2Svg = document.querySelector("#customer2Select");
let customer3Svg = document.querySelector("#customer3Select");
let customer4Svg = document.querySelector("#customer4Select");

 function toChair(custNum) {
  
 `customer${custNum}Svg`.classList.remove(`startPositionCustomer${custNum}`);
 `customer${custNum}Svg`.classList.remove(`moveCustomer${custNum}OffScreen`);
 `customer${custNum}Svg`.classList.add(`moveCustomer${custNum}ToChair`);
 }

    toChair(1);
    toChair(2);
    toChair(3);
    toChair(4);
Jupiter
  • 3
  • 3
  • 1
    I think you are trying to use a dynamically create variable name but you can't do that. Do you have variables like `customer1Svg`? Not clear what initial strings shown should reference. Provide some sample html and the code that stores the elements in the html you are trying to modify. See [mcve] – charlietfl Aug 29 '20 at 18:07
  • 2
    where are you using document.querySelector? – Asutosh Aug 29 '20 at 18:07
  • You should have an array variable `customerSvg` and then index into it with `custNum`. – Pointy Aug 29 '20 at 18:10
  • @charlietfl Thanks I edited my example, thanks to the feedback. – Jupiter Aug 29 '20 at 18:50
  • @Asutosh, thanks I forgot to add that in the example, just edited my post – Jupiter Aug 29 '20 at 18:51
  • @Pointy Thanks, that makes sense. Ill try to figure out a for loop that would make this work properly. – Jupiter Aug 29 '20 at 18:56
  • Use an object instead... `const custSvg = { 1: document.querySelector("#customer1Select")}` then in function `custSvg[custNum].classlist..` – charlietfl Aug 29 '20 at 18:57
  • Thanks @charlietfl. Will try that also. – Jupiter Aug 29 '20 at 18:58

0 Answers0