Last active
April 7, 2022 03:22
-
-
Save linhnobi/e659a37074c873c603bbad063d9c970c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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