Javascript: Set HTML lang attribute programmatically

Last updated on July 21, 2021 A Goodman Loading... 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.

Example

Preview

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">
  <head>
    <title>Kindacode.com</title>

    <script>
      const changeLang = (languageCode) => {
       document.documentElement.setAttribute("lang", languageCode);
      };
    </script>
  </head>
  <body>
    <div>
      <button onclick="changeLang('es')">Espanol</button>
      <button onclick="changeLang('en')">English</button>
      <button onclick="changeLang('fr')">French</button>
    </div>
  </body>
</html>

That’s it. Happy coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like