Pim
Pim

Reputation: 443

Testing for html lang attribute with jQuery

I'm using the following code to check for the lang attribute on the <html> element:

if( $("html:lang(en)") ){
  // Do something
}

I've noticed that this doesn't work consistently. For instance, when lang="fr", or when no language attribute is defined, the code still gets executed.

According to the jquery docs (https://api.jquery.com/lang-selector/), it should work. How come this isn't the case? And most importantly: How do I check which lang attribute is used in a consistent manner?

Upvotes: 1

Views: 1411

Answers (2)

edson alves
edson alves

Reputation: 231

You could also use [] selector and check the length property to know if it exists:

if ($("html[lang='en-us']").length) {
    //do something.
}

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

The $("html:lang(en)") would be always a truthy value since it returns a jQuery object. Instead, you need to check length property of returned object to check the element existence.

if($("html:lang(en)").length){
  //          here --^^^^^^^^--
  // Do something
}

Upvotes: 4

Related Questions