# Cannot find an element via JavaScript which does exist

**URL:** <https://meta.discourse.org/t/cannot-find-an-element-via-javascript-which-does-exist/257174>\
**Category:** Development\
**Created:** [March 6, 2023, 1:29am UTC](https://meta.discourse.org/t/cannot-find-an-element-via-javascript-which-does-exist/257174 "2023-03-06T01:29:14Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![awesomerobot](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/awesomerobot/32/142900_2.png) [@awesomerobot](https://meta.discourse.org/u/awesomerobot)\
**Post date:** [March 6, 2023, 7:48pm UTC](https://meta.discourse.org/t/cannot-find-an-element-via-javascript-which-does-exist/257174/2 "2023-03-06T19:48:27Z")

</div>

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…

```xml
<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…

---

_[View the full topic](https://meta.discourse.org/t/cannot-find-an-element-via-javascript-which-does-exist/257174)._
