Skip to content

Instantly share code, notes, and snippets.

@ginpei
Created December 20, 2017 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ginpei/5da142fd0996e10605e92233db2e4056 to your computer and use it in GitHub Desktop.
Save ginpei/5da142fd0996e10605e92233db2e4056 to your computer and use it in GitHub Desktop.
ページ中の単語を置き換える
{
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