Asked By: Anonymous
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!
Solution
Answered By: Anonymous
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');
}
_x000D_
<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>
_x000D_
_x000D_
x000D