-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation-to-the-DOM.ts
57 lines (49 loc) · 2.43 KB
/
translation-to-the-DOM.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Import the translations from a JSON file
import translateList from 'path/to/your_file.json';
// Define a Translation class that handles the translation process
class Translate {
/**
* Constructor to initialize the Translation class.
* @param {string} translateItem - The class name of the HTML element(s) to be translated.
* @param {string} translateFor - The text to be translated from.
* @param {string} translateTo - The text to translate to.
*/
constructor(private translateItem: string, private translateFor: string, private translateTo: string) {}
/**
* Method to perform the translation.
* It searches for all elements with the specified class name and replaces
* the inner text if it matches the `translateFor` value.
*/
translate(): void {
if (this.translateItem) {
// Select all elements with the specified class name
const translateItems: NodeListOf<HTMLDivElement> = document.querySelectorAll(`.${this.translateItem}`);
if (translateItems) {
// Iterate over each element and check if the text matches
for (const translateItem of translateItems) {
if (translateItem.innerText.toLowerCase() === this.translateFor.toLowerCase()) {
// Replace the inner text with the translation
translateItem.innerHTML = this.translateTo;
}
}
}
}
}
}
// Example Usage:
// Suppose we have some HTML like this:
// <div class="menu-item">Pork Ribs</div>
// <div class="menu-item">Steak</div>
// Let's assume `translateList` contains an array of translations like this:
// [
// { "translateItem": "menu-item", "translateFor": "Pork Ribs", "translateTo": "Свинині ребра" },
// { "translateItem": "menu-item", "translateFor": "Steak", "translateTo": "Стейк" }
// ]
// Iterate over the translation list and apply translations
translateList.forEach((item: { translateItem: string; translateFor: string; translateTo: string }) => {
const translator: Translate = new Translate(item.translateItem, item.translateFor, item.translateTo);
translator.translate(); // This will replace "Pork Ribs" with "Свинині ребра" and "Steak" with "Стейк"
});
// Resulting HTML after translation:
// <div class="menu-item">Свинині ребра</div>
// <div class="menu-item">Стейк</div>