Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save linhnobi/e659a37074c873c603bbad063d9c970c to your computer and use it in GitHub Desktop.
Save linhnobi/e659a37074c873c603bbad063d9c970c to your computer and use it in GitHub Desktop.
const replaceOnDocument = (pattern, string, { target = document.body } = {}) => {
[target, ...target.querySelectorAll("*:not(script):not(noscript):not(style)")]
.forEach(({ childNodes: [...nodes] }) => nodes
.filter(({ nodeType }) => nodeType === document.TEXT_NODE).forEach((textNode) => (textNode.textContent = textNode.textContent.replace(patter, string)))
);
replaceOnDocument("search","replace");
// retrives all childNodes of body
var childNodes = document.body.childNodes;
// start replacing
replaceInNodes(childNodes,"search","replace");
function replaceInNodes(nodes, search, replace) {
// iterate through all nodes
for (var i = 0; i < nodes.length; i++) {
var curNode = nodes[i];
// if the node has attributes, let us look at those
// i.E. we want to change "John" in the input placeholder to "Peter" - <input type="text" value="John">
if (curNode.attributes !== undefined) {
var curNodeAttributes = curNode.attributes;
for (var ii = 0; ii < curNodeAttributes.length; ii++) {
// replace attribute values
curNodeAttributes[ii].nodeValue = curNodeAttributes[ii].nodeValue.replace(search, replace);
}
}
// It is a "TEXT_NODE"
// i.E. <span>John</span>
if (curNode.nodeType == 3) {
curNode.data = curNode.data.replace(search, replace);
}
// It is a "ELEMENT_NODE", meaning we need to go deeper
if (curNode.nodeType == 1) {
this.replaceInNodes(curNode.childNodes, search, replace);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment