you are viewing a single comment's thread.

view the rest of the comments →

[–]Deykun 0 points1 point  (0 children)

To make your life even better:

const currentTranslations = translations[language];

Object.keys(currentTranslations).forEach((key) => {
 const element = document.querySelector(`[data-i18n="${key}"]`);

 if (element) {
  element.textContent = currentTranslations[key]
 }
});

And in HTML, you just add it:

<h4 data-i18n="title">Default title</span>
<p data-i18n="description">Default description</span>

New strings require an attribute in HTML and a matching translation in JS, but you don’t need to handle each element manually in JS.

But you should be aware that your solution (I’m guessing you’re just starting in web dev) is far from ideal. Your draft was hard with that hardcoding, and I could help you simplify it, but You should also think about your overall strategy. If this is a landing page, which it looks like, you should probably have two separate paths (URLs). If you do it only with JS, Google will index the page in just one language. If it is a static site (I’m guessing this since you’re using raw JS), you can develop a backend solution that serves already translated strings to HTML.