JavaScript: Set HTML lang attribute programmatically

Updated: February 19, 2023 By: Khue Post a comment

You can dynamically change the lang attribute of your HTML document just by using pure Javascript like this:

document.documentElement.setAttribute("lang", 'your language code');

For more clarity, take a look at the example below.



We are going to build a simple web app that contains 3 buttons. Each button is associated with a language code (en: English, es: Espanol, fr: French).

The Complete Code

<html lang="en">

      // this function will be called when a button is clicked
      const changeLang = (languageCode) => {
       document.documentElement.setAttribute("lang", languageCode);
      <button onclick="changeLang('es')">Espanol</button>
      <button onclick="changeLang('en')">English</button>
      <button onclick="changeLang('fr')">French</button>

That’s it. Happy coding!