In this tutorial we will learn How to get the lang attribute value with JavaScript. For this we can use the lang property or getAttribute() method, using them we can get the value of the lang attribute.
Table of Contents
lang property
lang property sets or returns the value of the lang attribute.
It is used to define the base language of the root element of the document.
getAttribute() method
getAttribute() method returns the value of the HTML attribute.
In this example we can use getAttribute() method to get value of lang attribute.
HTML Code
HTML Code is given below, in this code we have defined the base language of the page using lang attribute in the html tag. A button tag with onclick event is used to execute a function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Get the lang attribute value using JavaScript</title>
</head>
<body>
<button onclick="getValue()">Get Lang Value</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, two methods can be used to get the value of lang attribute.
In first example we have used documentElement property along with lang property to get lang value.
documentElement property returns the root element of the document. We have used this property because lang attribute is use inside the root element.
<script>
function getValue()
{
var value = document.documentElement.lang;
alert(value);
}
</script>
In second example we have used getElementsByTagName() method with getAttribute() method.
getElementsByTagName() method is used to select or target the html tag. While getAttribute() method will provide it's value of lang attribute.
<script>
function getValue()
{
var value = document.getElementsByTagName("html")[0].getAttribute("lang");
alert(value);
}
</script>
To get the lang value with the namespace.
<script>
function getValue()
{
var value = document.getElementsByTagName("html")[0].getAttribute("xml:lang");
alert(value);
}
</script>
Demo
Video Tutorial
Watch video tutorial on How to get value of the lang attribute using JavaScript.