Created
August 15, 2023 11:05
-
-
Save ryo88c/16c6c1859e01228e718fb1d7eac7f5ac to your computer and use it in GitHub Desktop.
指定したDOM配下の任意の文字列を置換する関数
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
export default (rootElement, lang = 'ja') => { | |
const texts = [ | |
{ | |
before: new RegExp('Parallel translation', 'g'), | |
after: { ja: '対訳' } | |
}, | |
]; | |
const translate = node => { | |
for (let i = 0; i < texts.length; i++) { | |
if (node.nodeValue.match(texts[i].before)) { | |
node.nodeValue = node.nodeValue.replace(texts[i].before, texts[i].after[lang]); | |
break; | |
} | |
} | |
} | |
const dig = node => { | |
if (node.nodeType === Node.ELEMENT_NODE) { | |
for (let i = 0; i < node.childNodes.length; i++) { | |
dig(node.childNodes[i]); | |
} | |
} else if (node.nodeType === Node.TEXT_NODE) { | |
translate(node); | |
} | |
} | |
const observer = new MutationObserver((targetNodes, observer) => { | |
for (let i = 0; i < targetNodes.length; i++) { | |
dig(targetNodes[i].target) | |
} | |
}); | |
observer.observe(rootElement, { childList: true, subtree: true }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment