0

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!

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I will try this. To be honest with you, the problem is a little bit more complex than my question. I asked for jQuery solution but I am working on server side translation with PHPQuery, a library that my company uses as a sort of templating engine. I hate it :D And, I just need to translate the emails we send to our customers, I call our Database for registered translation and an API the new ones which are then stored into the DB too. Thanks again, if your answer solves the problem I will mention it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.