Javascript: How to extract language from <html lang="...">

If your have a HTML page with the lang attribute set:

example.html
<html lang="de">
<!-- ... -->
</html>

you can extract the language code using Javascript like this:

example.js
const lang = document.documentElement.lang;

In case you want to specify a default language, use this variant:

example.js
const lang = document.documentElement.lang || 'en';

This will default to 'en' if the lang attribute is not set.


Check out similar posts by category: Javascript, Internationalization