Detect html lang with jQuery

Dan382 picture Dan382 · Nov 11, 2015 · Viewed 8.8k times · Source

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?

Answer

Stryner picture Stryner · Nov 11, 2015

Your selector is correct, but you're using it in the if statement incorrectly.

$( 'html:lang(en-us)') will return a jQuery object. jQuery objects are always truthy, so your if statement will always evaluate to true.

A simple fix is to use the .is function, which will return a boolean:

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