# 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:** 1

<div class="post-metadata">

**Author:** ![darkpixlz](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/darkpixlz/32/549896_2.png) [@darkpixlz](https://meta.discourse.org/u/darkpixlz)\
**Post date:** [March 6, 2023, 1:29am UTC](https://meta.discourse.org/t/cannot-find-an-element-via-javascript-which-does-exist/257174/1 "2023-03-06T01:29:14Z")

</div>

Hello,

I tried making a script to grab the background-image attribute from the profile header, then save it as a root variable. However, my code does not work. I tried many solutions, some of them included AI, which just reverted the plugin version and did not help.

This is the code:

```js
<script type="text/discourse-plugin" version="0.9">
    const setRootBgImage = () => {
        try {
            const el = document.getElementByClassName('.user-profile-image');
            if (el) {
                const bgImage = window.getComputedStyle(el).getPropertyValue('background-image');
                document.documentElement.style.setProperty('--profile-bg-img', bgImage);
            }
        } catch (error) {
            console.error(error);
            debugger; //when run, this always comes up no matter what and displays the same error
        }

    };

    const shouldRun = () => {
        return window.location.pathname.startsWith('/u/');
    };

    const init = () => {
        if (shouldRun()) {
            setRootBgImage();
        }
    };

    document.addEventListener('DOMContentLoaded', init);

    api.onPageChange(() => {
        init();
    });
</script>

```

Thank you.

---

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