A likely cause is that the HTML code doesn’t yet exist when the JavaScript code is running.
The usual technique is to place scripting at the end of the body, that helps to alleviate such issues.
But, your situation is one where the code doesn’t even seem to exist until after the popup has done its thing.
Details of how that popup does its thing is required. A link to an appropriate page that lets us experience the problem is most suited here.