Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract lang value using JavaScript

Tags:

javascript

I am trying to get the lang value from the HTML tag, but the current JavaScript I am using doesn't work.

This is the HTML code I am trying to access:

<html  lang="it-IT">

And the Javascript

if(navigator.appName == 'Netscape')
{
    langType = navigator.language;
}
else
{
    langType = navigator.browserLanguage;
}

but in testing I still get the value "EN-us"

Can anyone help?

Thanks!

like image 382
BoredOfBinary Avatar asked Mar 19 '09 16:03

BoredOfBinary


People also ask

How can I get Lang in Javascript?

To read the html element lang attribute value with JavaScript, we can use the getElementsByTagName and getAttribute methods. to call getElementsByTagName to get the html element object. Then we call html. getAttribute with 'lang' to get the lang attribute value of the html element.

What is Lang property in Javascript?

The lang property sets or returns the value of an element's lang attribute. The lang attribute specifies the element's language code, like "en" for English, "es" for Spanish, or "fr" for French.

How can get html lang attribute value in jquery?

$("html"). attr("lang") works just fine for me when extrapolating from the example you have given. Can you post more details? check if all your scripts are running (with firebug - see if no error); and also your html is valid.

How can I get the HTML language of a webpage?

The HTMLElement. lang property gets or sets the base language of an element's attribute values and text content. The language code returned by this property is defined in RFC 5646: Tags for Identifying Languages (also known as BCP 47).


2 Answers

Use

document.documentElement.lang

As Rob has commented, your code gets the browser's language and not the document's.

like image 166
Christoph Avatar answered Oct 21 '22 17:10

Christoph


try this

var language = document.getElementsByTagName("html")[0].getAttribute("lang");

I haven't tried it, but it should work.

like image 23
nickytonline Avatar answered Oct 21 '22 16:10

nickytonline