How to set HTML lang attribute dynamically?

Xplora picture Xplora · Feb 3, 2016 · Viewed 15.4k times · Source

How to set HTML 'lang' attribute dynamically in a web application?

I tried using jQuery as follows to insert the 'lang' attribute:

Using console/alert, 'lang' attribute looks to be set as expected. But if you see generated source (View Source), 'lang' isn't getting set at all.

Requirement is Screen Readers must be able to recognize the language dynamically. It would be great if there is any other solution to make Screen Readers recognize the language dynamically. Thanks everyone for the comments inline!

Answer

ShortFuse picture ShortFuse · May 6, 2020

document.documentElement.setAttribute('lang', navigator.language);

or

document.documentElement.lang = navigator.language;