What’s the purpose of the lang attribute in HTML ?

When creating an an HTML document, we would include the lang attribute to specify the language of the content within the document.

This allows browsers, screen readers etc. to correctly interpret and present content and allows screen readers to pronounce words in the style of the language selected. So for example we’d have

<!DOCTYPE html>
<html lang="en">
  <!-- content -->
</html>

Note that we use the short form language, i.e. “en” or long form such as “en-GB” or “en-US”

Obviously this would need to be changed if your application support i18n, so we might use something like the following, if we’re using something like the i18n package for React

document.documentElement.lang = i18n.language;

// OR

document.documentElement.lang = i18n.resolvedLanguage;

If you do not set the lang or set it to an empty string this simply means the language is unknown.

Whilst this post talks about the html tag, you can actually set the lang on other elements, such as paragraphs p so on a per element basis.