Amir E. Aharoni
Amir E. Aharoni

Reputation: 1318

How to find out the computed value of an element's lang attribute in JavaScript?

I sometimes need to find out the computed value of the HTML lang attribute (the element's language). I'm using jQuery. For example, in the following code I'd like to know the computed lang of the <p> element, and I would expect the value he:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8" />
        <title>lang test</title>
    </head>
    <body>
        <div lang="ar">
            <div lang="he">
                <p>Hallo.</p>
            </div>
        </div>
    </body>
</html>

Doing $( 'p' ).attr( 'lang' ) returns nothing, probably because the <p> element doesn't have its own lang attribute.

This code seems to do the right thing:

 $( 'p' ).closest( '[lang]' ).attr( 'lang' )

Is this functionally correct? And is there a better way to do it in jQuery, in pure JavaScript or with another JavaScript library?

Thank you.

Upvotes: 5

Views: 460

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201588

The simplest way is to write a recursive function:

function getLanguage(node) {
  if(node.lang) {
    return node.lang;
  } else if(node.parentNode) {
    return getLanguage(node.parentNode);
  } else {
    return undefined;
  }
}

Recursion might be inefficient at times, but here it probably does not matter.

If you need the information for various elements in a document very frequently, efficiency might be relevant, and then you could traverse the entire document tree and add a new property, indicating the “computed language” to each node.

Upvotes: 1

Alnitak
Alnitak

Reputation: 339816

This jQuery plugin should do the job. It only considers the first element in the jQuery object.

(function($) {
    $.fn.lang = function() {
         if (this.length) {
             var node = this[0];
             while (node) {
                 if (node.lang) {
                     return node.lang;
                 }
                 node = node.parentNode;
             }
         }
    };
})(jQuery)

It will return undefined if no lang attribute is found.

Upvotes: 0

Related Questions