The issue is that your RequestEEFormData function uses $.ajax, but it does not return a promise that resolves after container.innerHTML is updated. As a result, loadScript runs immediately after calling RequestEEFormData, before the DOM is actually updated. To fix this, you should wrap your AJAX request inside a promise and resolve it after setting container.innerHTML. That way, you can guarantee that the new HTML is rendered before loading and running your script. Right now, your then() is not really waiting for the DOM update, which is why querySelector returns null at first.