5

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.

2
  • 2
    I think you wrote the best way. Ofcourse, if you use jQuery in other code a lot. Commented May 11, 2013 at 15:04
  • .prop() could be used instead of .attr() Commented May 11, 2013 at 15:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Lol. You use jQuery but forget about closest and jQ selectors like in original post. You're funny, dude
@moredemons jQuery [lang] attribute selectors may not work if the language property was added as a property instead of an attribute. It depends on whether the browser mirrors the property into the attribute. Chrome does, I don't know about other browsers. In any event, this would be more efficient than using an attribute selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.