Localization With Javascript

Akifcan Kara
2 min readMar 20, 2021

Hello in this article we are going to change app language with Javascript.

Start

First we need some language files. I concat the file name with language code and json extension. Like this.

All in the language file one thing will be have to same. Key value. With key value we will detect the html elements which we want to translate.

de.json

{

“hello”: “Hallo”,

“localization”: “Lokalisierung “,

“with”: “Mit Javascript “

}

en.json

{

“hello”: “Hello”,

“localization”: “Localization”,

“with”: “With javascript”

}

tr.json

{

“hello”: “Merhaba”,

“localization”: “Yerelleştirme”,

“with”: “Javascript ile”

}

fr.json

{

“hello”: “Bonjour”,

“localization”: “Localisation”,

“with”: “Avec javascript”

}

ja.json

{

“hello”: “こんにちは”,

“localization”: “ローカリゼーション”,

“with”: “Javascriptで “

}

now we can create the html elements.

As you can see all elements which we want to localize has data-text attribute and data-text attribute equal with the key values.

In javascript file i created a function called language. This function takes one argument (language code). And with this argument we are access to json file.

Object.keys

For access keys of value we can use Object.keys and we will have a output like this.

Object.keys(language)

As you can see Object.keys return the array so we can use forEach.

Object.keys(language).forEach(item => {

console.log(item);

})

Also if you want to access value then we can use :

console.log(language[item])

Now we will detect the html elements match the key value.

Object.keys(language).forEach(key => {

const element = document.querySelector(`[data-text=”${key}”]`)

element.textContent = language[key]

})

We found html elements with data-text and key now we can change the textContent or innerHTML

--

--