Andrew Vermie
Andrew Vermie

Reputation: 633

How to determine an element's language with Javascript?

According to the spec, language is inherited from the nearest ancestor element which has lang set. So how do I get the language of one of these descendents?

I'm setting the language with the lang attribute:

<div id="outer" lang="es">
    <div id="inner">¿Por qué?</div>
</div>

And trying to access it with the lang property:

alert(document.getElementById('outer').lang);
alert(document.getElementById('inner').lang);

I pretty quickly noticed that the lang property of the inner div isn't the inherited language (or it's not inheriting; no idea). This fiddle demonstrates the behavior I'm seeing.

How can I determine an element's language with Javascript? I'm really looking to take advantage of the inheritance of the lang attribute, as I also need this to work with screen-readers.

Upvotes: 5

Views: 581

Answers (2)

maerics
maerics

Reputation: 156384

Here is a function that will return the value of the "lang" attribute of the nearest ancestor of any element, or undefined if none is found:

function elementLang(el) {
  while (el) {
    if (el.hasAttribute('lang')) {
      return el.getAttribute('lang');
    }
    el = el.parentElement;
  }
}

// From your example jsFiddle...
elementLang(document.getElementById('inner')); // => "es"
elementLang(document.getElementById('outer')); // => "es"
elementLang(document.getElementById('output')); // => undefined

Upvotes: 1

Etheryte
Etheryte

Reputation: 25310

From the very spec you linked to:

To determine the language of a node, user agents must look at the nearest ancestor element (including the element itself if the node is an element) that has a lang attribute in the XML namespace set or is an HTML element and has a lang in no namespace attribute set. That attribute specifies the language of the node (regardless of its value).

Inheriting from another element doesn't mean the attribute is set for the element itself. Therefore, your code must, as well, find the nearest parent with the lang attribute (if any exist). See this question if that sounds problematic.

Upvotes: 3

Related Questions