Cannot find an element via JavaScript which does exist

Your script is loading before most of the page is rendered, so it can’t find the element…

This should get you what you’re looking for…

<script type="text/discourse-plugin" version="0.9">
api.onPageChange(() => {
  let currentRouteParent = api.container.lookup("router:main").currentRoute?.parent;
    if (currentRouteParent.name.includes("user")) {
        let userBg = currentRouteParent.attributes.profile_background_upload_url;

        if (userBg) {
            document.documentElement.style.setProperty('--profile-bg-img', userBg);
        } else {
            document.documentElement.style.removeProperty('--profile-bg-img');
      }
    }
});
</script> 

I assume you’re trying to reuse the user’s profile background on the profile page somewhere? otherwise this won’t stick around if you navigate away from a profile and refresh the page…