I missed that the error was only in the editor.
Basically what happens is that in preview mode the code is executed by the preview iframe inside the editor. In the editor instead the code lives in the main editor page that does not have the elements of your app page because they are inside the preview iframe.
This is one tricky thing to remember when you add custom javascript in weweb.
There are some unofficial helpers in wwLib
for this.