Finally, by looking at other scripts on other J3 sites, I find that I have to wrap the code like this and it works:
// original code as above
(although I still have the cross-site cookie notices, but I think that's another issue...)
I'm not sure why it would be working in J4, but not J3. That said, you're unecessarily using nested for loops, rather than a single forEach iterator.
You can use the following:
// Create an array using Array.from(), so that we can filter later on
const toggles = Array.from(document.querySelectorAll('.toggle-form'));
// Iterate over the array