Simplest Possible Internationalization with Vanilla JavaScript

DOM elements (li) with language-dependent text are going to be marked with the data-i18 data attributes (or any attribute of your choice):


<ol>
    <li data-i18n>over</li>
    <li data-i18n>under</li>
    <li>duke</li>
</ol>

The internationalized values are maintained in a JavaScript object, which could be loaded from server with fetch as JSON:

const germanConfig = {
    under: "unter",
    over: "ueber"
}

Now the querySelectorAll function can be used to locate DOM elements with language-specific text contents:

const elements = document.querySelectorAll("[data-i18n]");    
...and replaced with the following function:

const replaceText = (el) => { 
    const key = el.innerText;
    el.innerText = germanConfig[key] || key;
}    
elements.forEach(el => replaceText(el));

See it in action and "from scratch":

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

Comments:

New learning. Thanks

Posted by Arulraj on November 03, 2019 at 03:18 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License