125

How to obtain lang attribute in HTML using JavaScript?

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

3 Answers 3

251

If both attributes agree on their values (as they should), it's enough to read either of them. I'd suggest using

document.documentElement.lang
Sign up to request clarification or add additional context in comments.

4 Comments

Does this fetch the xml:lang or the lang attribute?
@KrisSelbekk: should be the lang attribute, but I haven't done anything to verify this...
This will not work with xml:lang Ref : Dev mozilla
Note that this won't retrieve the inherited lang property.
34

Just.

document.getElementsByTagName('html')[0].getAttribute('lang');

And with the namespace

document.getElementsByTagName('html')[0].getAttribute('xml:lang');

1 Comment

This will correctly return the lang of the html element of the document, that is inherited by the html node descendants. But, anywhere any element can have its own lang, perhaps different from its ancestors', and spread it downwards. In most cases there will be a single lang, albeit it's not sure.
1

If you would like to get the value of the lang attribute of an element, then you can simply access the lang property in JavaScript:

console.log(element.lang);

However, this won't retrieve the inherited lang value. For that, you will need to find the closest parent with a lang attribute yourself, like this.

function getLang(el) {
  const closest = el.closest('*[lang]:not([lang=""])');
  if (closest) {
    return closest.lang;
  }
}

for (const el of document.querySelectorAll("button")) {
  el.addEventListener("click", () => {
    alert(getLang(el));
  });
}
<div lang="en">
  <button>First</button>
  <div lang="fr">
    <button>Second</button>
  </div>
  <button lang="it">Third</button>
</div>
<button>Fourth</button>

1 Comment

This is the only correct answer. Even if the page is set to one language, sections of it still can be in another language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.