1

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?

2 Answers 2

4

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

Comments

1

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

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

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.