Sling Academy
Home/JavaScript/JavaScript: Set HTML lang attribute programmatically

JavaScript: Set HTML lang attribute programmatically

Last updated: February 19, 2023

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>
      // this function will be called when a button is clicked
      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!

Next Article: JavaScript: 4 Ways to Get the Width & Height of an Element

Previous Article: The Modern JavaScript DOM Cheat Sheet

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration