Pim Pim - 10 months ago 54
HTML Question

Testing for html lang attribute with jQuery

I'm using the following code to check for the

attribute on the

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

I've noticed that this doesn't work consistently. For instance, when
, 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
attribute is used in a consistent manner?

Answer Source

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.

  //          here --^^^^^^^^--
  // Do something