Pim Pim - 3 days ago 5
HTML Question

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?

Answer

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
}
Comments