Dan382
Dan382

Reputation: 986

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?

Upvotes: 4

Views: 16054

Answers (6)

Mr Coder
Mr Coder

Reputation: 523

this is working for me in WordPress

jQuery(document).ready(function($){ console.log("cons"); if ( $("html:lang(en)").length > 0 ) {
   alert( 'US lang detected' );
} });

Upvotes: 0

Karthik Ganesan
Karthik Ganesan

Reputation: 4222

You have to check for length:

if ( $("html:lang(en-us)").length > 0 ) {
    alert( 'US lang detected' );
}

Upvotes: 2

Sampson
Sampson

Reputation: 268334

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.

Upvotes: 5

Stryner
Stryner

Reputation: 7318

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');
}

Upvotes: 8

mapodev
mapodev

Reputation: 988

$('html[lang="en-us"]')

should do it.

Upvotes: 1

edonbajrami
edonbajrami

Reputation: 2206

You can grab the lang as attr, like the code in snippet

console.log($("html").attr("lang"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html lang="en">
<head></head>
  <body></body>
</html>

Upvotes: 0

Related Questions