How to set HTML 'lang' attribute dynamically in a web application?
I tried using jQuery as follows to insert the 'lang' attribute:
$(document).ready(function() {
$("html").attr("lang", language); //'language' value is retrieved from a cookie
});
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!
You can dynamically change the lang attribute of your HTML document just by using pure Javascript like this: For more clarity, take a look at the example below. We are going to build a simple web app that contains 3 buttons. Each button is associated with a language code (en: English, es: Espanol, fr: French). That’s it.
The lang attribute specifies the language of the element's content. Common examples are "en" for English, "es" for Spanish, "fr" for French and so on. The lang attribute is a Global Attribute, and can be used on any HTML element.
When the page contains content in another language, add a language attribute to an element surrounding that content. Use the lang attribute for pages served as HTML, and the xml:lang attribute for pages served as XML. For XHTML 1.x and HTML5 polyglot documents, use both together.
Always use a language attribute on the html tag to declare the default language of the text in the page. When the page contains content in another language, add a language attribute to an element surrounding that content. Use the lang attribute for pages served as HTML, and the xml:lang attribute for pages served as XML.
document.documentElement.setAttribute('lang', navigator.language);
or
document.documentElement.lang = navigator.language;
But if you see generated source (View Source), 'lang' isn't getting set at all.
View Source doesn't show you the generated source. It shows you the real source. If you want to change it, then you need to change it on the server before you deliver it to the browser. You can't modify it with client side JavaScript.
Your DOM changes will show up in the live DOM, which will be visible through Inspect Element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With