Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 736
Amir E. Aharoni Avatar asked Nov 12 '22 05:11

Amir E. Aharoni


1 Answers

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.

like image 75
Jukka K. Korpela Avatar answered Nov 14 '22 22:11

Jukka K. Korpela