In JavaScript, the best way to get the document language is to use:
document.documentElement.lang;
You can also retrieve the preferred language settings from the browser using the navigator
object:
navigator.language || navigator.userLanguage;
Another option is to retrieve the <html>
tag lang
attribute:
To detect the language of a web page in JavaScript, you can use the navigator
object, which provides information about the browser and the user's environment. Specifically, you can access the navigator.language
or navigator.languages
properties.
Here's how you can do it:
navigator.language
You can detect the language of a webpage in JavaScript using the navigator.language
property. This property returns a string representing the preferred language of the user, usually the language of the browser's UI.
Here's how you can use it:
// Get the preferred language of the user
let userLanguage = navigator.language || navigator.userLanguage;
console.log("The user's language is: " + userLanguage);
navigator.language
will typically return a string in the format of a language code, such as:
"en"
for English"fr"
for French"es"
for Spanish"en-US"
for English as used in the United StatesIf you need to detect the language of the HTML document itself, you can access the lang
attribute of the HTML element:
// Get the language of the document
let pageLanguage = document.documentElement.lang;
console.log("The page's language is: " + pageLanguage);
In this case, document.documentElement.lang
will return the value of the lang
attribute from the HTML <html>
tag. For example:
<html lang="en">
In the above case, the output would be "en"
.
You can also retrieve the lang
attribute using:
document.getElementsByTagName("html")[0].getAttribute("lang");
navigator.languages
This returns an array of the user's preferred languages in order of preference.
let userLanguages = navigator.languages;
console.log(userLanguages); // e.g., ["en-US", "fr", "de"]
let userLanguage = navigator.language || navigator.userLanguage;
let pageLanguage = document.documentElement.lang;
console.log("User's preferred language: ", userLanguage);
console.log("Page language: ", pageLanguage);
This approach allows you to access both the user's language preference and the language declared in the HTML of the web page. Here is an online example: