0

I want to replace all the occurrences of a certain string in a web page's body without replacing the entire body (as it could destroy eventlisteners etc). Is there a way to do this and if so, what is the best one?

To give an example:

We have the following code:

<body>
    <div class="header">
        #parameter#
    </div>
    <div class="body">
        <div class="some-widget">
            we have some code here
            <div class="text">
                And also our #parameter#
            </div>
        </div>
    </div>
</body>

As mentioned, we could use something like

$('body').html($('body').html().replace(/#parameter#/g, 'Our parameter value'));

but that could render our some-widget useless.

We have no idea what the web page will look like structurally, so we cannot look for certain containers of our #parameter#

Ideally, I think we would perform a search on "#parameter#", get the parent element and then replace the parent elements html in the way mentioned above. I do not know if and how that is possible however. The closest I got was This question, but it didn't get me much further.

Thanks!

Mats Raemen
  • 1,781
  • 1
  • 28
  • 41

1 Answers1

2

You can iterate over all text nodes and replace their nodeValue:

function getTextNodes(parent) {
    const walker = document.createTreeWalker(
        parent,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );

    let node;
    const nodes = [];

    while(node = walker.nextNode()) {
        nodes.push(node);
    }
    return nodes;
}

for (const node of getTextNodes(document.body)) {
  node.nodeValue = node.nodeValue.replaceAll('#parameter#', 'foo');
}
<body>
    <div class="header">
        #parameter#
    </div>
    <div class="body">
        <div class="some-widget">
            we have some code here
            <div class="text">
                And also our #parameter#
            </div>
        </div>
    </div>
</body>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320