Cannot find an element via JavaScript which does exist

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:

<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.

2 Likes

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…

2 Likes

That worked! Seems like ths css doesn’t though.
image

1 Like

Ah right, what you’ll want to do is add the url() part to the custom property value… so something like:

document.documentElement.style.setProperty('--profile-bg-img', `url(${userBg})`);
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.