Home / Uncategorised / Replace Text via JS

Replace Text via JS

Matthew L

Add the following into a Cope Snippets custom JS snippet.

This will replace the phrase

Hello world

with

Goodbye world

<script>
document.addEventListener("DOMContentLoaded", function () {
    function replaceTextInElements() {
        document.querySelectorAll("p, div, span").forEach(element => {
            if (element.innerText.trim() === "Hello world") {
                element.innerText = "Goodbye world";
            }
        });
    }

    // Run once after page load
    replaceTextInElements();

    // Observe for dynamically added content
    const observer = new MutationObserver(replaceTextInElements);
    observer.observe(document.body, { childList: true, subtree: true });
});
</script>

If your text is in a heading ect update the query selector

Eg below includes h3

document.querySelectorAll("p, div, span, h3").forEach(element => {

If you need to change multiple items of text use the following

<script>
document.addEventListener("DOMContentLoaded", function () {
    function replaceTextInElements() {
        document.querySelectorAll("p, div, span").forEach(element => {
            let text = element.innerText.trim();

            if (text === "Change one") {
                element.innerText = "to this text";
            } 

            if (text === "Change second") {
                element.innerText = "to this aswell";
            }
        });
    }

    // Run once after page load
    replaceTextInElements();

    // Observe for dynamically added content
    const observer = new MutationObserver(replaceTextInElements);
    observer.observe(document.body, { childList: true, subtree: true });
});
</script>