How to obtain lang attribute in HTML using JavaScript?
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
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
xml:lang or the lang attribute?lang attribute, but I haven't done anything to verify this...xml:lang Ref : Dev mozillalang property.Just.
document.getElementsByTagName('html')[0].getAttribute('lang');
And with the namespace
document.getElementsByTagName('html')[0].getAttribute('xml:lang');
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>