Search code examples
jqueryhtmlmultilinguallang

Detect html lang with jQuery


I'm using a multilingual plugin in Wordpress that enables users to change their language options on a website.

This plugin among other things changes the HTML language attribute e.g.

<html lang="en-GB">

or

<html lang="en-US">

I've tried to detect the language using the following selector:

if ($( 'html:lang(en-us)')) {
    alert('US lang detected');
}

However this creates a false positive as other elements further down the page are set to 'en-us' even if the opening HTML attribute is set to 'en-GB'.

What selector would specifically examine only the opening HTML attribute?


Solution

  • By using jQuery for a task like this, you may be making things unnecessarily complicated and slow:

    if ( document.documentElement.lang.toLowerCase() === "en-us" ) {
        alert( "American English." );
    }
    

    Vanilla JavaScript is better for menial tasks like reading an attribute value, etc.