Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTML lang attribute dynamically?

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!

like image 476
Xplora Avatar asked Feb 03 '16 21:02

Xplora


People also ask

How to dynamically change the lang attribute of an HTML document?

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.

What is lang attribute in HTML?

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.

How do I add a language attribute to an HTML 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. For XHTML 1.x and HTML5 polyglot documents, use both together.

How do I change the default language of an HTML page?

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.


2 Answers

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

or

document.documentElement.lang = navigator.language;

like image 177
ShortFuse Avatar answered Sep 23 '22 11:09

ShortFuse


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.

like image 20
Quentin Avatar answered Sep 25 '22 11:09

Quentin