JavaScript로 존재하는 요소를 찾을 수 없습니다

안녕하세요,

프로필 헤더에서 background-image 속성을 가져와 루트 변수로 저장하는 스크립트를 작성해 보았습니다. 하지만 제 코드가 작동하지 않습니다. 다양한 해결책을 시도해 보았는데, 그중 일부는 AI를 사용했는데, 결과적으로 플러그인 버전만 되돌려졌을 뿐 도움이 되지 않았습니다.

아래는 제 코드입니다:

<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; //실행할 때 항상 이 에러가 발생하며 동일한 오류가 표시됩니다
        }

    };

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

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

    document.addEventListener('DOMContentLoaded', init);

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

감사합니다.

스크립트가 페이지의 대부분이 렌더링되기 전에 로드되고 있으므로 요소를 찾을 수 없습니다…

다음 방법으로 원하는 결과를 얻을 수 있습니다…

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

사용자의 프로필 배경을 프로필 페이지의 다른 곳에 재사용하려는 것 같습니다. 그렇지 않으면 프로필에서 다른 곳으로 이동하거나 페이지를 새로고침하면 유지되지 않습니다…

그렇게 하면 작동했어요! 그런데 이 CSS는 그렇지 않은 것 같아요.
image

아 맞다, 커스텀 프로퍼티 값에 url() 부분을 추가해야 합니다… 예를 들어 다음과 같이 말이죠:

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