Reputation: 71
I would like to know how I could parse the DOM using jQuery and modify the text of each node in order to translate a page of my site. Using jQuery is a constraint, not a choice :)
To be more precise, I would like to go through the DOM, to target each node which contains text, to translate it using an API and to replace the original text with the translated one.
I feel a little bit lost even if it seems pretty simple. Thanks for your help!
Upvotes: 0
Views: 132
Reputation: 2771
If I get you correctly, you will have something like
// use $('*') instead if you really want to use jQuery
Array.from(document.querySelectorAll('*')).forEach(async _ => {
_.textContent = await myTranslationApi(_.textContent);
});
However, I will have to say that it a) is slow to render the page with the wrong language and then replace it (this could also lead to flash of untranslated text) and b) might be error-prone to simply feed the textContent
into your translation API (you probably want to search for translation keys and only replace them).
Upvotes: 1