Change single instance of icon

Thanks for pointing that out — you’re absolutely right. Using api.onPageChange alone can be unreliable since it fires on route change, not after DOM rendering. That means there’s a race condition risk where the #create-topic button might not exist yet when the script tries to access it.

 api.onPageChange(() => {
        const targetSelector = "#create-topic";

        const tryEnhanceButton = () => {
            const button = document.querySelector(targetSelector);

            if (button) {
                // Disconnect observer after finding the element
                observer.disconnect();

                // Temporarily hide the button while we replace the icon
                button.style.display = "none";

                // Remove old icon if exists
                const oldIcon = button.querySelector("svg");
                if (oldIcon) oldIcon.remove();

                // Create and insert new Font Awesome SVG icon
                const newIcon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
                newIcon.setAttribute("class", "fa d-icon d-icon-feather-pointed svg-icon svg-string");
                newIcon.setAttribute("xmlns", "http://www.w3.org/2000/svg");
                newIcon.innerHTML = '<use href="#feather-pointed"></use>';

                button.insertBefore(newIcon, button.firstChild);

                // Show the button again
                button.style.display = "block";
            }
        };

        // Observe changes to the DOM and try to enhance the button when it's added
        const observer = new MutationObserver(() => tryEnhanceButton());
        observer.observe(document.body, { childList: true, subtree: true });

        // Try immediately as well in case it's already there
        tryEnhanceButton();
    });

@Don I’ve included MutationObserver to ensure the script only runs once the target element actually exists, it disconnects itself after doing its job to avoid unnecessary overhead. It still attempts an immediate check in case the element already exists.

I’m unable to fetch the svg I want from the Discourse icon system, although i registered it admin SVG icon subset as it seems it’s in fontawesome but not in discourse.

1 Like