Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
Dan382 Avatar asked Sep 05 '25 11:09

Dan382


2 Answers

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');
}
like image 178
Stryner Avatar answered Sep 08 '25 11:09

Stryner


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.

like image 41
Sampson Avatar answered Sep 08 '25 11:09

Sampson