Do javascript for loops work in html templates?

I am trying to do something like this:

const paths = document.querySelectorAll(‘#kvg\:09b31 path’);

let hue = 200

paths.forEach (path => { = "hsl( " + hue + ", 100%, 50%)";
  hue += 35;


Is it possible or not in anki html templates ?

so I have to do it like this:


const paths = document.querySelectorAll(‘#kvg\:09b31 path’);
let hue = 200;

for (let i = 0; i < paths.length; i++) {

paths[i].style.stroke = “hsl(” + hue + “, 100%, 50%)”;

  hue += 35;



but the changes dont always appear in the template editor

Idk much about Javascript, but see Anki recommendations when using Javascript

yeah there is nothing about for loops in there

Anki desktop (and maybe AnkiMobile) only updates part of the page when flipping cards, so redeclaring a variable already declared with const or let in the global namespace (i.e. at the top level of the script) will cause an error.

You can try either of the following:

  • Replace let and const in the first two lines with var
  • Wrap the whole code in curly braces (or in IIFE) to prevent polluting the global namespace

the script that i am importing with anki connect is actually working with let and const

I’m using quite a bit of (plain) Javascript and it works pretty well for me. Note that you can use hacks like delaying code execution with

setTimeout(function() {
  //your code to be executed after delayInMilliseconds
}, delayInMilliseconds);

(if you don’t want to show the changes being applied, you can set display to none first and then set it to block afterwards; that way you only get a small delay when showing the card, which is quite tolerable)

For example, in a test deck I wanted to randomly rotate an image (and had to do the same rotation for the back side) and that delayed code execution was the thing that saved the day.
Talking about using Javascript, the anki-persistence code by Simon Lammers is suuuper useful.

I was asking this question because I was having quite a bit of trouble with inserting variables inside backticks into strings inside my script. Then I also had to include a promise event listener because my script was working only on the first card of the deck.

Hm, I don’t have much experience with backticks, but what I can get from a 5s Google search is that they’re a somewhat special feature (for literals?). My advice is to prepare the data outside of Anki and only use basic JavaScript commands in Anki. Then it should work fine. (At least that’s my experience so far…)

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.