Created
December 20, 2017 03:26
-
-
Save ginpei/5da142fd0996e10605e92233db2e4056 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
{ | |
replaceWords(/猫/g, '犬'); | |
function replaceWords(target, result) { | |
const texts = []; | |
const els = document.querySelectorAll('title, body *:not(script):not(style)') | |
els.forEach(el => { | |
texts.push(...findTextNodes(el)) | |
}) | |
texts.forEach(text => { | |
text.nodeValue = text.nodeValue.replace(target, result) | |
}) | |
} | |
function findTextNodes(node) { | |
const texts = []; | |
if (node.nodeType === node.TEXT_NODE) { | |
texts.push(node) | |
} | |
else if (node.nodeType === node.ELEMENT_NODE) { | |
node.childNodes.forEach(node => { | |
texts.push(...findTextNodes(node)) | |
}) | |
} | |
return texts; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment