4

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?

1
  • 1
    Use $('html[lang="en-us"]') Commented Nov 11, 2015 at 17:23

6 Answers 6

8

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');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining things, it's much appreciated. Went with a plain Javascript solution as advised by another comment, however this would have also done the job.
5

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.

1 Comment

Thanks, I appreciate the feedback. The Javascripts handling the job perfectly.
2

You have to check for length:

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

1 Comment

Since positive numbers are truthy in JavaScript, you could remove the >0 portion of the conditional statement, and the code would be equally valid. (just be careful with negative numbers)
1
$('html[lang="en-us"]')

should do it.

Comments

0

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>

Comments

0

this is working for me in WordPress

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

Comments

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.