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.


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

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