How to Read HTML lang Attribute in JavaScript
-
Get
lang
Attribute asdocumentElement
in JavaScript -
Get
lang
Attribute WithgetElementByTagName
in JavaScript -
Use jQuery
attr
Method to Get thelang
Attribute
In this article, we will examine 3 examples that will return the value of the lang
attribute. In this case, the observation is to which convention we can refer for this value.
Get lang
Attribute as documentElement
in JavaScript
We will have a basic HTML setup, and the lang
attribute will be set with a value. In our JavaScript section, we will grab the instance for the attribute by the document.documentElement
.
Code - HTML:
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>language</title>
</head>
<body>
</body>
</html>
Code - JavaScript:
var lang = document.documentElement.lang;
console.log(lang)
Output:
Get lang
Attribute With getElementByTagName
in JavaScript
The drive is similar to the previous one. The difference is in how we grab the instance of the lang
attribute.
We will use document.getElementByTagName("html")[0]
as the indexed portion defines the first element. As the document.getElementByTagName
by default returns an array of objects.
Code - HTML:
<!DOCTYPE html>
<html lang>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>language</title>
</head>
<body>
</body>
</html>
Code - JavaScript:
var lang = document.getElementsByTagName('html')[0].getAttribute('lang');
console.log(lang)
Output:
Any value did not follow the lang
attribute, and thus an empty value was printed.
Use jQuery attr
Method to Get the lang
Attribute
We will add the jQuery library to take help from its method attr
. Through this function, we can call the lang
attribute from the HTML.
Code Snippet:
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>language</title>
</head>
<body>
<script>
var lang = $('html').attr('lang');
console.log(lang);
</script>
</body>
</html>
Output:
We can see, along with the language code, that there is an uppercase code. This 2 letter code refers to the country code, often used to specify the language category.