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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With