Translate Website/Webapp With JavaScript and/or jQuery and XML


Having completed a web application, or website, in your native language, comes the necessity to localize it in another language, to make it accessible outside your country too. If you have hard-coded strings in your pages (which you've probably done, especially for labels and/or all-purpose messages), a task like this could be pretty eerie to accomplish (primarily depending on project size, or complexity level).

Here we'll see a fast and easy method to alter a webpage's DOM, using a custom resource file to modify our strings inside predetermined elements. We'll see how to do that using plain JavaScript first, then jQuery.

A simple page

Here follows the HTML of a simple page, showing some element's values written in Italian. Please note that all the elements have an ID. That's fundamental for when we come to the scripting part.
  1. <html>  
  2.    <head>  
  3.       <title>Translate Website/Webapp with JS and XML</title>  
  4.    </head>  
  6.    <body>  
  7.       <h1 id="AppTitle">Titolo applicazione</h1>  
  9.       <span id="GenText">Testo generico con fini dimostrativi</span><br/>  
  10.       <span id="EndText">Testo di chiusura</span>  
  12.       <div id="DivText">  
  13.          Testo contenuto in un div.  
  14.       </div>  
  15.    </body>  
  16. </html>  
Opening it in a browser, our page will resemble the following:

Making a string resource file


In a hypothetical string resource file, we want to introduce all of our app's strings. We can create a set of XML entities having attributes complying with our HTML elements. In other words, exploiting the JavaScript function to access DOM's elements by their ID, we could think of pairing a given HTML ID with its XML counterpart. For example, based on the previous page example, we could jot down a resource file like the following: 
  1. <strings>  
  2.    <string id="AppTitle"     en = "Application's Title"/>  
  3.    <string id="GenText"      en = "Generic text with demonstrative means"/>     
  4.    <string id="EndText"      en = "Closing text"/>  
  5.    <string id="DivText"      en = "Div contained text"/>  
  6. </strings>  

For each string entity, we've defined two attributes. The first, id, corresponds to a specific ID in HTML code, while the second one, "en", contains an English translation of our elements. The logic behind this is simple. When our page finishes loading, we need a JavaScript to be fired up in order to read our DOM's IDs, replacing their innerHTML with the one specified in XML "en" attribute.

We'll save the preceding example as "translate.xml", for further use.

Replace text using JavaScript

The first function we'll provide is about reading our XML file, using XMLHttpRequest (or XMLHTTP, if on IE). Check the following: 
  1. function loadXMLDoc(filename){  
  2.    if (window.XMLHttpRequest){  
  3.       xhttp = new XMLHttpRequest();  
  4.    } else {  
  5.       xhttp = new ActiveXObject("Microsoft.XMLHTTP");  
  6.    }  
  8.    xhttp.send();  
  9.    return xhttp.responseXML;  
  10. }  
Finally, the localize() function must be fired up after the complete load of our page, to ensure all the elements will be rendered/accessible. We could simply add an explicit call to localize() after the closing of body tag, in the following way:
  1. <!-- omissis -->  
  2.    </body>  
  4.    <script>  
  5.       localize();  
  6.    </script>  
  7. </html>  
You could refer to the file "sample01.html" in the source code for the full example. Running our page again, we'll see the text will be replaced as in the following:
Important: It's advisable to run the presented code in a web server environment (IIS or Apache), because the opening of our XML file could end up in a cross-origin request exception otherwise.

Replacing text using jQuery

Using jQuery will result in a more compact script, in which we can rely on asynchronicity and specify to await for a complete load in a single location (typically, the HEAD section). The entire script seen above could be replaced with the following:
  1. <script src=""></script>  
  3. <script>  
  4.    $(document).ready(function(){  
  5.       $.ajax({  
  6.          type: "GET" ,  
  7.          url: "translate.xml" ,  
  8.          success: function(xml) {  
  9.              $(xml).find('string').each(function(){  
  10.                 var item_id = $(this).attr("id");  
  11.                 $("#" + item_id).text($(this).attr("en"));  
  12.              });  
  13.          }  
  14.       });  
  15.    });  
  16. </script>  
Here, after finishing the loading of the page, our script will proceed in an AJAX call to our trasnalte.xml file and upon success in accessing it, it will loop through "string" entities, using the "id" and "en" attributes to refer to which DOM element must be targeted and replacing their inner HTML with the one of our choice. Please refer to the "sample02.html" file in the given source code.


Far from declaring the ultimate method to localize a website or webapp, we saw a pratical and quick method to do that. The quality of such an approach resides indisputably in the minimum interventions necessary in the original source code, assuming an ID naming approach has been used at the development stage. I hope you'll find it useful.

Up Next
    Ebook Download
    View all
    View all