How to Read HTML lang Attribute in JavaScript

Anika Tabassum Era Feb 02, 2024
  1. Get lang Attribute as documentElement in JavaScript
  2. Get lang Attribute With getElementByTagName in JavaScript
  3. Use jQuery attr Method to Get the lang Attribute
How to Read HTML lang Attribute in JavaScript

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 as documentElement

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:

Get lang Attribute with getElementByTagName

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:

Use jQuery attr Method to Get the lang Attribute

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.

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook